2016-03-19 23 views
-3

私は周期表を持つファイルを取得し、それを関数readfileに入れてファイルを読みます。しかし、table1を印刷すると、(null)0が印刷されます。どうして?なぜ私は 'c'でヌルを出力するのですか

#define SIZE 200 

void readfile(FILE *fp1, char ***table1, int ***graph) {  
    int counter = 0; 
    int i; 
    char table[SIZE]; 
    if (fp1 == NULL) { 
     printf("The file is incorrect\n"); 
     exit(EXIT_FAILURE); 
    } 
    while ((fgets(table, SIZE, fp1)) != NULL) { 
     counter++; 
    } 
    (*table1) = (char **)malloc(counter); 
    (*graph) = (int**)malloc(counter); 
    for (i = 0; i < counter; i++) { 
     (*table1) = (char *)malloc(counter); 
     (*graph) = (int *)malloc(sizeof(int) * counter); 
    } 
    int j = 0; 
    while ((fgets(table, SIZE, fp1)) != NULL) { 
     sscanf(table,"%s %d\n", (*table1)[j], &i); 
     j++; 
    } 
    printf("%s%d\n", (*table1)[j]); 
} 

int main(int argc, char *argb[]) { 
    FILE *fp1; 
    fp1 = fopen(argb[1], "r"); 
    char **table1 = NULL; 
    int **graph = NULL; 
    readfile(fp1, &table1, &graph); 
    return 0; 
} 
+0

あなたは '*'あまりにも多くを持っています。 – pmg

+1

3つ星のプログラマであることは、Cの賛辞ではありません – Olaf

+2

http://c2.com/cgi/wiki?ThreeStarProgrammerまたはhttp://c2.com/cgi/wiki?YouMightBeaThreeStarProgrammerおよびhttp://c2.com/cgi/wiki?ThreeStarProgrammerExamples – pmg

答えて

1

あなたのコードで複数の問題があります。

  • あなたはおそらく間違っているトリプルポインタを渡します。
  • 配列や文字列に正しい量のメモリを割り当てることはありません。
  • 最初の読み取りループの後にファイルrewind()はありません。
  • メモリ割り当ての失敗を確認しません。
  • ファイル形式の不一致を確認しません。ここで

修正バージョンです:

#include <stdio.h> 
#include <stdlib.h> 

#define SIZE 200 

void *xalloc(size_t size) { 
    void *p = malloc(size); 
    if (p == NULL) { 
     fprintf(stderr, "memory allocation failure\n"); 
     exit(EXIT_FAILURE); 
    } 
    return p; 
} 

int readfile(FILE *fp1, char ***tablep, int **graphp) { 
    int i, counter = 0; 
    char buf[SIZE]; 
    char **table; 
    int *graph; 

    if (fp1 == NULL) { 
     printf("The file is incorrect\n"); 
     exit(EXIT_FAILURE); 
    } 
    // count how many lines 
    while (fgets(buf, sizeof buf, fp1) != NULL) { 
     counter++; 
    } 
    table = xalloc(sizeof(*table) * counter); 
    graph = xalloc(sizeof(*graph) * counter); 
    rewind(fp1); 
    for (i = 0; i < counter && fgets(buf, sizeof buf, fp1) != NULL; i++) { 
     table[i] = xalloc(strlen(buf) + 1); 
     if (sscanf(table, "%s %d", table[i], &graph[i]) != 1) { 
      fprintf(stderr, "file format error at line %d\n", i + 1); 
      break; 
     } 
    } 
    *tablep = table; 
    *graphp = graph; 
    return i; 
} 

int main(int argc, char *argv[]) { 
    FILE *fp1; 
    char **table = NULL; 
    int *graph = NULL; 
    int count = 0; 

    if (argc > 2) { 
     fp1 = fopen(argv[1], "r"); 
     count = readfile(fp1, &table, &graph); 
     printf("read %d records\n", count); 
    } 
    return 0; 
} 
関連する問題