2017-10-30 6 views
1

こんにちは、私は別のファイルからの値を読み、いくつかの例外を除いて、別のファイルにそれらを表示すべきCでプログラムを作成しようとしているが作成されます。私が得ている問題は、空である結果配列の一部を読み込もうとしているときに起こるセグメンテーションフォールトです。私のForループはファイルをすべての行についてスキャンし、この特定のファイルの行が自分のニーズに合っていれば、値は配列に保存されます。この配列は2番目の.txtファイルに出力する必要があります。テスト用に配列の値をいくつかprintfしたかったのです。私は配列やポインタの間違いだと思う。C:動的配列とポインタ配列は、セグメンテーションフォールト

/* 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. 

}

+0

'result' 'char **'として定義されていますが、 'char'として割り当てて' char * 'にキャストしています。 mallocの戻り値を 'C'にキャストしないでください。 – MFisherKDX

答えて

1

あなたは間違ってresultに配分されています。 MAX_LAENGE_ARR*sizeof(char)バイトを割り当てています。 MAX_LAENGE_ARR*sizeof(char *)バイトを割り当てる必要があります。また、戻り値mallocを間違った型にキャストしています。警告をオンにしてコンパイルすると、コンパイラはこのエラーを捕らえたはずです。しかし、あなたはC.でmallocDo I cast the result of malloc?

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

の戻り値をキャストする必要はありません。また、私はあなたが次の行でMAX_LAENGE_STRMAX_LAENGE_ARRを交換する必要があると思う:

snprintf(result[i], MAX_LAENGE_ARR, "Die Stadt %s hat %d Einwohner.", staedte[i], bewohner[i]); 
関連する問題