我在寫一個程序,我需要連接兩個數組。如何連接指針數組
例如,如果我有:
int max =100;
char *append = "Hello";
char *pStr = malloc(max);
我將如何串聯append
到pStr
?
我在寫一個程序,我需要連接兩個數組。如何連接指針數組
例如,如果我有:
int max =100;
char *append = "Hello";
char *pStr = malloc(max);
我將如何串聯append
到pStr
?
不,你不能。分配後,您無法更改大小。
你要做的是分配一個新的空間(足夠大以容納兩者),並將其複製到它。
char* str1 = "Hello";
char* str2 = "World";
char* con = (char*) calloc(strlen(str1) + strlen(str2) + 1, sizeof(char));
strcpy(con, str1);
strcpy(con + strlen(str1), str2);
fprintf("%s\n", con); // "HelloWorld"
使用可以在這兩者之間進行選擇:在你的榜樣
char *pStr = malloc(max);
char* str1 = "Hello ";
char* str2 = "Wor";
char* str3 = "ld";
strcpy(pStr, str1);
strcat(pStr, str2);
strcat(pStr, str3);
或
char *pStr = malloc(max);
char* str1 = "Hello ";
char* str2 = "Wor";
char* str3 = "ld";
pStr[0] = '\0';
strcat(pStr, str1);
strcat(pStr, str2);
strcat(pStr, str3);
strcpy(pStr, append);
或
pStr[0] = '\0';
strcat(pStr, append);
strcpy
不需要\0
。它只是複製目標字符串(加上'\ 0')。
strcat
將目標字符串連接到源字符串。來源必須爲空終止那就是爲什麼pStr[0] = '\0'
。
max
必須足以容納所有的字符串加上終止字符\0
瓦爾特
'pStr'目前不包含字符串,所以你不能追加到它。你能否舉一個例子來說明事後的情況? –
你難以理解副本和連接嗎?有兩個函數可以執行 - 'strcpy'來複制和'strcat'來連接。 –