我只是想 malloc 一个字符串数组并将文件中的输入复制到这个数组中。这种行组合会导致段错误,我不知道为什么。
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
s:
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);
}