C 在字符串数组中将字符追加到字符串时出现分段错误
所以我想从一个文件中获取所有行,并将它们转换为char*数组。问题是,每当我尝试将字符附加到元素的末尾时,它都会导致分割错误C 在字符串数组中将字符追加到字符串时出现分段错误,c,arrays,string,pointers,char,C,Arrays,String,Pointers,Char,所以我想从一个文件中获取所有行,并将它们转换为char*数组。问题是,每当我尝试将字符附加到元素的末尾时,它都会导致分割错误 char** loadOutputs(char *fileName, int *lineCount) { FILE *file = fopen(fileName, "r"); if (file) { char c; int lines = 0; while ((c = fgetc(file)) != EOF) if (c =
char** loadOutputs(char *fileName, int *lineCount)
{
FILE *file = fopen(fileName, "r");
if (file) {
char c;
int lines = 0;
while ((c = fgetc(file)) != EOF)
if (c = '\n')
lines++;
rewind(file);
char **output = malloc(lines * sizeof(char*));
for (int i = 0; i < lines; i++)
output[i] = "";
int index = 0;
while ((c = fgetc(file)) != EOF)
if (c == '\n')
index++;
else
strcat(output[i], &c);
return output;
}
return NULL;
}
我总是在strcatoutput[I]、&c;处出现分段错误;。我不希望为输出创建固定的数组大小,因为这可能会变得相当大,并且我不想使用太多内存。以下代码:
for (int i = 0; i < lines; i++)
output[i] = "";
此外,还需要将c声明为和int,即将char c更改为int c。这是因为EOF超出了char的范围,输出[i]指向字符串文字,不允许更改&c不是终止字符串。这两个事实都可能导致SEGFULT。这里有几个问题。一个是所有的输出[i]指针都指向您无法修改的固定字符串。您必须分别为每行分配malloc空间。而且,strcat不适用于单个字符。它需要一个以nul结尾的字符串。
for (int i = 0; i < lines; i++) {
output[i] = malloc(MAX_LINE_LENGTH + 1);
}
int index = 0;
int position = 0;
while ((c = fgetc(file)) != EOF) {
if (c == '\n') {
output[index][position] = 0; // Null terminate the line
position = 0; // Restart next line
index++;
} else {
if (position < MAX_LINE_LENGTH) { // Check if we have space!
output[index][position] = c; // Add character and move forward
position++;
}
}
}
output[index][position] = 0; // Add the null to the final line