ความหมาย
strcat() นำต่อ (concatenate) string ต้นทาง (src) ไปยังปลายทาง (dest) ทั้งหมด
Prototype
char *strcat(char *dest, const char *src);
เงื่อนไข
- dest ต้องมีพื้นที่เพียงพอสำหรับ string เดิม + src + null terminator
- ผลลัพธ์เก็บใน dest
ตัวอย่างโปรแกรมที่ 1: ต่อ String แบบง่าย
#include <stdio.h>
#include <string.h>
int main() {
char a[50] = "Hello ";
char b[20] = "Good Morning";
strcat(a, b);
printf("string ที่ต่อแล้ว = %s\\n", a);
return 0;
}ผลลัพธ์
string ที่ต่อแล้ว = Hello Good Morning
ตัวอย่างโปรแกรมที่ 2: รับ Input จากผู้ใช้
#include <stdio.h>
#include <string.h>
int main() {
char source[45], destination[50];
printf("ป้อน source string: ");
fgets(source, sizeof(source), stdin);
source[strcspn(source, "\\n")] = '\\0';
printf("ป้อน destination string: ");
fgets(destination, sizeof(destination), stdin);
destination[strcspn(destination, "\\n")] = '\\0';
strcat(source, destination); // ต่อ destination เข้า source
printf("source ที่ต่อแล้ว: %s\\n", source);
return 0;
}ผลลัพธ์ตัวอย่าง
ป้อน source string: Tutorials Point ป้อน destination string: C programming source ที่ต่อแล้ว: Tutorials Point C programming
ความเสี่ยงและการป้องกัน
Buffer Overflow: หาก dest ไม่พอรองรับ จะเขียนทับหน่วยความจำถัดไป -> undefined behavior
วิธีป้องกัน
- ใช้
strncat(dest, src, sizeof(dest) - strlen(dest) - 1) - หรือใช้
snprintfแทน - คำนวณขนาด buffer ให้พอเสมอ
ตารางเปรียบเทียบ
| ฟังก์ชัน | Header | คำอธิบาย |
|---|---|---|
| strcat | string.h | ต่อ string ทั้งหมด |
| strncat | string.h | ต่อ n ตัวอักษร (ปลอดภัยกว่า) |
| sprintf/snprintf | stdio.h | จัดรูปแบบและต่อ string ได้ยืดหยุ่นกว่า |
หมายเหตุ
- ต้อง include
<string.h> - src ไม่เปลี่ยนแปลง dest เปลี่ยนแปลง
- ไม่ควรใช้ gets() ใช้ fgets() แทน