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;
}
答案 0 :(得分:3)
nameList = malloc(4*sizeof(char*));
之后你有:
nameList [0] =垃圾
nameList [1] =垃圾
nameList [2] =垃圾
nameList [3] =垃圾
你有nameList[0] = "Hello ";
之后
nameList [0] =“你好”
nameList [1] =垃圾
nameList [2] =垃圾
nameList [3] =垃圾
所以,当你执行strcat(nameList[1], "World");
时,你很可能会得到一个段错误,因为nameList [1]可以指向内存中的任何位置。
答案 1 :(得分: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);
答案 2 :(得分:0)
在使用双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;
}