簡體   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