【发布时间】: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。