【发布时间】:2020-05-19 12:39:29
【问题描述】:
我尝试创建一个 char 指针的动态数组,指针也可以是动态内存是什么意思,所以在上面的代码中,我尝试为数组分配一个大小,在他中,为第一个对象分配一个字符串.但我在数组指针上收到错误“检测到堆损坏”。
int main(void)
{
char** pArr = 0;
char string[] = "hello";
pArr = (char**)malloc(sizeof(char) * 1); //make it an array with one element
*pArr = (char*)malloc(sizeof(char) * (strlen(string) + 1)); //make it an array with the size of string
strcpy(*pArr, string); //copy string to the first element of the array
printf("%p", pArr); //the pointer where the heap corruption is detected
free(pArr);
getchar();
return 0;
}
我复制了整个主目录,所以你知道我没有预料到这一点。
【问题讨论】:
-
使用 pArr = (char**)malloc(sizeof(char *));
-
* 1毫无意义,只会使代码混乱。
标签: c dynamic-memory-allocation pointer-to-pointer arrayofarrays arrayofstring