char *strcat(char *string1, const char *string2);
功能把string2連接在string1之後。
函式會回傳string1的位址
程式碼
#include <string.h> #include <stdio.h> int main() { char String1[12] = "hello"; char String2[6] = "World"; char * ptr; printf("befor strcat\n"); printf("String1:%s\n",String1); printf("String1 Size:%d\n\n",sizeof(String1)); ptr = strcat(String1,String2); printf("After strcat\n\n"); printf("String1:%s\n",String1); printf("String1 address:%p\n\n",String1); printf("String1 Size:%d\n\n",sizeof(String1)); printf("ptr address:%p\n",ptr); printf("ptr :%s\n",ptr); return 0; }
在使用上需要去注意string1的陣列長度是否足夠,否則會發生問題,將string1的大小由12改成6,並執行下面程式碼測試
#include <string.h> #include <stdio.h> int main() { char String1[6] = "hello"; char String2[6] = "World"; char * ptr; printf("befor strcat\n"); printf("String1:%s\n",String1); printf("String1 Size:%d\n\n",sizeof(String1)); ptr = strcat(String1,String2); printf("After strcat\n\n"); printf("String1:%s\n",String1); printf("String1 address:%p\n\n",String1); printf("String1 Size:%d\n\n",sizeof(String1)); printf("ptr address:%p\n",ptr); printf("ptr :%s\n",ptr); return 0; }
我們可以看到字串印出來怪怪的
參考資料
https://www.ibm.com/docs/en/i/7.1?topic=functions-strcat-concatenate-strings
https://zh.m.wikipedia.org/zh-tw/String.h#%E5%87%BD%E6%95%B0
https://www.tutorialspoint.com/c_standard_library/c_function_strcat.htm
沒有留言:
發佈留言