[英]What's wrong with this simple code using strings, malloc and strcat?
char**
總是讓我困惑。 以下代碼生成分段錯誤。 請解釋...
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char** nameList;
nameList = malloc(4*sizeof(char*));
nameList[0] = malloc(12); //not sure if needed but doesn't work either
nameList[0] = "Hello ";
printf("%s ",nameList[0]);// even this statement isn't executed
strcat(nameList[0], "World");
printf("%s ",nameList[0]);
return 0;
}
在nameList = malloc(4*sizeof(char*));
你有:nameList [0] = trash nameList [1] = trash nameList [2] = trash nameList [3] = trash
在nameList[0] = "Hello ";
你有nameList [0] =“Hello”nameList [1] = trash nameList [2] = trash nameList [3] = trash
所以當你做strcat(nameList[1], "World");
你很可能會得到一個段錯誤,因為nameList [1]可以指向內存中的任何位置。
您的代碼通過寫入只讀存儲來展示未定義的行為,並且還嘗試寫入它的末尾。
您的malloc
理念是朝着正確方向邁出的一步。 但是,您應該使用strcpy
將"Hello"
復制到新分配的內存中。 此外,您需要考慮計划追加的字符串的大小,以及計算動態分配大小時的空終止符。
顯然,您還需要在程序結束時釋放所有已分配的內存:
char** nameList;
nameList = malloc(4*sizeof(char*));
nameList[0] = malloc(12);
strcpy(nameList[0], "Hello ");
printf("%s ",nameList[0]);
strcat(nameList[0], "World"); // You were strcat-ing into a wrong element
printf("%s ",nameList[0]);
free(nameList[0]);
free(nameList);
在使用雙ptrs之前,獲取使用單個ptr的代碼。 此外,您不希望“過度編程”簡單的代碼。 但是,如果要編寫double ptr的用法,請從此代碼開始並修改為使用雙ptrs。
int main()
{
char *nameList;
nameList = malloc(12); // point nameList to 12 bytes of storage
strncpy(nameList, "Hello \0", 7);
printf("%s\n",nameList); // notice no space, its already after hello
strncat(nameList, "World", 5);
printf("%s\n",nameList);
free(nameList);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.