我无法理解如何分配内存
到一个双指针.
我想读一个字符串数组并存储.
到一个双指针.
我想读一个字符串数组并存储.
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);
会是错的吗如果是这样,为什么呢?
解决方法
你的第二个例子是错误的,因为每个内存位置在概念上不会持有一个char *而是一个char.如果你稍微改变你的想法,它可以帮助你:
char *x; // Memory locations pointed to by x contain 'char' char **y; // Memory locations pointed to by y contain 'char*' x = (char*)malloc(sizeof(char) * 100); // 100 'char' y = (char**)malloc(sizeof(char*) * 100); // 100 'char*' // below is incorrect: y = (char**)malloc(sizeof(char) * 50 * 50); // 2500 'char' not 50 'char*' pointing to 50 'char'
因此,您的第一个循环将是您如何在C数组的字符数组/指针.对于一个字符数组,使用一个固定的内存块就可以了,但是你将使用一个char *而不是一个char **,因为你不会在内存中有任何指针,只是字符.
char *x = calloc(50 * 50,sizeof(char));
for (ii = 0; ii < 50; ++ii) {
// Note that each string is just an OFFSET into the memory block
// You must be sensitive to this when using these 'strings'
char *str = &x[ii * 50];
}