gpt4 book ai didi

c - 将字符附加到字符串数组中的字符串时出现段错误

转载 作者:行者123 更新时间:2023-11-30 14:53:10 25 4
gpt4 key购买 nike

所以我想从文件中获取所有行并将它们转换为 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 = '\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;
}

我总是在 strcat(output[i], &c); 处遇到段错误。我不想为输出创建固定的数组大小,因为这可能会变得相当大,而且我不想使用太多内存。

最佳答案

以下代码:

for (int i = 0; i < lines; i++)
output[i] = "";

正在将指针设置为空只读字符串。

您需要为字符串分配一些内存:

for (int i = 0; i < lines; i++) {
output[i] = malloc(MAX_LINE_LENGTH + 1);
}

其中 MAX_LINE_LENGTH 是某个已定义的常量 - 也许是 #define MAX_LINE_LENGTH 100

您需要检查在阅读这些行时是否没有超过此长度。

以下代码将执行此操作。这将解决另一个问题,即 c 的地址不会指向以 null 结尾的字符串。

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

您还需要将 c 声明为 int - 即将 char c 更改为 int c。这是因为 EOF 超出了 char

的范围

关于c - 将字符附加到字符串数组中的字符串时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47366486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com