我不太明白如何给一个双指针分配内存。我想读取一个字符串数组并将其存储。
char **ptr;
fp = fopen("file.txt","r");
ptr = (char**)malloc(sizeof(char*)*50);
for(int i=0; i<20; i++)
{
ptr[i] = (char*)malloc(sizeof(char)*50);
fgets(ptr[i],50,fp);
}
我不是这样做的,而是分配一大块内存并将字符串存储在其中。
char **ptr;
ptr = (char**)malloc(sizeof(char)*50*50);
那样做会有错吗?如果有,为什么会错?
malloc()
、realloc()
或calloc()
的调用结果进行强制类型转换 - 这是不必要的,而且可能掩盖了缺少原型的严重错误。 - mlp