我只是想错误地放置一个字符串数组并将输入从文件复制到这个数组中。这种线条组合会导致段错误,我不知道为什么。
int count = 0;
char **output = (char**)malloc(numLines*257);
fgets(output[count], 257, input);
您已经为指针数组分配了空间,但尚未初始化其中任何指针。
int count = 0;
char **output = malloc(numLines*sizeof(char *));
int i;
for (i = 0; i < numLines; i++) {
output[i] = malloc(257);
}
fgets(output[count], 257, input);
我认为您在这里真正想做的是为numLines
指针(字符串(分配内存,然后为每个字符串分配内存,以便每个字符串都能够保存257
char
:
int i, count = 0;
char **output = malloc(sizeof(char*) * numLines);
for (i = 0; i < numLines; ++i)
output[i] = malloc(257);
...
fgets(output[count], 257, input);
只是一旦不再需要它,请不要忘记清理它:
for (i = 0; i < numLines; ++i)
free(output[i]);
free(output);
output = NULL;
int count = 0;
char **output = (char**)malloc(numLines*257);
fgets(output[count], 257, input); // here You are going wrong, with out allocating memory you are trying to read.
如果要读取字符串
char *output = malloc(MAX_LENGTH+1); //allocate memory
fgets(output[count], MAX_LENGTH+1, input);
如果要读取字符串数组
char **output = malloc(MAX_NUM_STRINGS * sizeof(char *)); //allocate Number of pointers
for(count=0;count<MAX_NUM_STRINGS;count++)
{ output[count]=malloc(SIZE_OF_EACH_STRING+1); //allocate memory for each pointer,
//You are accessing with out allocating memory
fgets(output[count], SIZE_OF_EACH_STRING+1, input);
}