Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

ฟังก์ชัน strcpy() ในภาษา C

ความหมาย

strcpy() คัดลอก string ต้นทาง (src) ไปยังปลายทาง (dest) รวม null terminator

Prototype

char *strcpy(char *dest, const char *src);

เงื่อนไข

  • dest ต้องมีขนาด >= ความยาว src + 1 (สำหรับ null terminator)
  • ผลลัพธ์เก็บใน dest

Syntax

strcpy(dest, src);

ตัวอย่างการใช้งาน

char a[50];
strcpy(a, "Hello"); // ถูกต้อง: a = "Hello"
strcpy("Hello", a); // ผิด: string literal ไม่สามารถเขียนได้

ตัวอย่างโปรแกรมที่ 1: คัดลอก String พื้นฐาน

#include <stdio.h>
#include <string.h>
int main() {
    char a[50], b[50];
    printf("ป้อน source string: ");
    scanf("%s", a); // อ่านจนกว่าจะเจอ space
    strcpy(b, a);
    printf("string ที่คัดลอก = %s\\n", b);
    return 0;
}

ผลลัพธ์

ป้อน source string: Hello
string ที่คัดลอก = Hello

ตัวอย่างโปรแกรมที่ 2: ใช้ fgets รับ string ที่มี space

#include <stdio.h>
#include <string.h>
int main() {
    char source[25], destination[50];
    printf("ป้อน string ที่ต้องการคัดลอก: ");
    fgets(source, sizeof(source), stdin);
    source[strcspn(source, "\\n")] = '\\0';
    printf("ป้อน destination string เดิม: ");
    fgets(destination, sizeof(destination), stdin);
    destination[strcspn(destination, "\\n")] = '\\0';
    strcpy(destination, source);
    printf("destination string ใหม่: ");
    puts(destination);
    return 0;
}

ผลลัพธ์

ป้อน string ที่ต้องการคัดลอก: C programming
ป้อน destination string เดิม: bhanu
destination string ใหม่: C programming

ความเสี่ยงและทางเลือกที่ปลอดภัยกว่า

Buffer Overflow: strcpy ไม่ตรวจสอบขนาด dest

ทางเลือกที่ปลอดภัย

ฟังก์ชันคำอธิบาย
strncpy(dest, src, n)คัดลอกสูงสุด n ตัวอักษร (แต่อาจไม่เติม null terminator)
snprintf(dest, size, "%s", src)ปลอดภัยที่สุด รับประกัน null terminator และไม่ overflow
strlcpy (BSD)คัดลอกพร้อม size limit และ null terminator เสมอ (non-standard)

หมายเหตุ

  • ต้อง include <string.h>
  • src ไม่เปลี่ยนแปลง dest เปลี่ยนแปลง
  • ทับซ้อน (overlap) ระหว่าง src และ dest -> undefined behavior (ใช้ memmove แทน)