【问题标题】:C: Dynamic Array and Pointer array creates Segmentation faultC:动态数组和指针数组造成分段错误
【发布时间】:2018-04-10 22:20:23
【问题描述】:

您好,我正在尝试用 C 语言创建一个程序,它应该从另一个文件中读取值并将它们显示在另一个文件中,但有一些例外。我遇到的问题是分段错误,当我试图读取我的结果数组的一部分时,它是空的。我的 For 循环扫描文件的每一行,如果这个特定文件中的一行符合我的需要,它的值应该保存在一个数组中。该数组应打印在第二个 .txt 文件中。我想 printf 我的数组的一些值用于测试目的。我猜这是我的数组或指针的错误。

/* 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 定义为char **,但您分配为char 并转换为char *。不要将 malloc 的返回值投射到C

标签: c arrays pointers malloc


【解决方案1】:

您分配给result 不正确。您正在分配 MAX_LAENGE_ARR*sizeof(char) 字节。您需要分配MAX_LAENGE_ARR*sizeof(char *) 字节。此外,您将 malloc 的返回值转换为错误的类型。如果您在打开警告的情况下进行编译,则编译器应该已经发现了这个错误。但是,您不需要在 C 中强制转换 malloc 的返回值。Do I cast the result of malloc?

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

另外,我认为您需要在以下行中将 MAX_LAENGE_ARR 替换为 MAX_LAENGE_STR

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

【讨论】:

    猜你喜欢
    • 2013-10-03
    • 1970-01-01
    • 2013-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多