簡體   English   中英

C:動態數組和指針數組創建分段錯誤

[英]C: Dynamic Array and Pointer array creates Segmentation fault

你好,我正在嘗試用 C 創建一個程序,它應該從另一個文件中讀取值並將它們顯示在另一個文件中,但有一些例外。 我遇到的問題是分段錯誤,當我嘗試讀取空的結果數組的一部分時會發生該錯誤。 我的 For 循環為每一行掃描一個文件,如果這個特定文件中的一行符合我的需要,它的值應該保存在一個數組中。 這個數組應該打印在第二個 .txt 文件中。 我想為測試目的打印數組的一些值。 我想這是我的數組或指針中的錯誤。

/* Die Konstanten:
 *  int MAX_LAENGE_STR - die maximale String Länge
 *  int MAX_LAENGE_ARR - die maximale Array Länge
 *  sind input3.c auf jeweils 255 und 100 definiert
 */
int main(int argc, char **argv) {
        if (argc < 3) {
            printf("Aufruf: %s <anzahl> <bundesland>\n", argv[0]);
            printf("Beispiel: %s 100 Bayern\n", argv[0]);
            printf("Klein-/Großschreibung beachten!\n");
            exit(1);
        }
        int anzahl = atoi(argv[1]);
        char *bundesland = argv[2];

// Statisch allokierter Speicher
char staedte[MAX_LAENGE_ARR][MAX_LAENGE_STR];
char laender[MAX_LAENGE_ARR][MAX_LAENGE_STR];
int bewohner[MAX_LAENGE_ARR];

int len = read_file("staedte.csv", staedte, laender, bewohner);

// Hier implementieren
int j;
char** result = (char *) malloc (MAX_LAENGE_ARR * sizeof(char));
if (result == NULL) {
    perror("malloc failed while allocating memory");
    exit(1);
    } 
for (int i = 0; i < len; i++) {
    if (strcmp(bundesland, laender[i]) == 0 && *bewohner > anzahl) {
        result[i] = malloc(MAX_LAENGE_STR * sizeof(char));
        if (result == NULL) {
            perror("malloc failed while allocating memory");
            exit(1);
        }
        snprintf(result[i], MAX_LAENGE_ARR, "Die Stadt %s hat %d Einwohner.", staedte[i], bewohner[i]);
        //printf("%s\n", result[i]);
    }
} 
printf("%s", result[0]);
// Mithilfe von write_file(...) soll das Ergebnis in die "resultat.txt"
// geschrieben werden. 
write_file(result, len);
// Dynamisch allozierter Speicher muss hier freigegeben werden.

}

您分配的result不正確。 您正在分配MAX_LAENGE_ARR*sizeof(char)字節。 您需要分配MAX_LAENGE_ARR*sizeof(char *)字節。 此外,您將malloc的返回值轉換為錯誤的類型。 如果你編譯時打開警告,編譯器應該已經發現了這個錯誤。 但是,你不需要在 C 中轉換malloc的返回值。 我是否轉換了 malloc 的結果?

char** result = malloc (MAX_LAENGE_ARR * sizeof(*result));

另外,我認為您需要在以下行中用MAX_LAENGE_STR替換MAX_LAENGE_ARR

snprintf(result[i], MAX_LAENGE_ARR, "Die Stadt %s hat %d Einwohner.", staedte[i], bewohner[i]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM