繁体   English   中英

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

[英]Segmentation fault when appending char to string in string array

所以我想从文件中获取所有行,并将它们转换为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);遇到分段错误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的地址不会指向以空终止的字符串。

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的范围

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM