我尝试创建一个 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;
}
我复制了整个主要内容,所以你知道我没有预料到这一点。