为什么它在'c'中将我打印为null

时间:2016-03-19 16:50:23

标签: c

我得到一个带有周期表的文件,然后将它放在函数readfile中,然后我读取了该文件。但是当我打印table1时,它会打印(null)0。为什么呢?

#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;
}

1 个答案:

答案 0 :(得分:1)

您的代码存在多个问题:

  • 您传递graph的三重指针,这可能不正确。
  • 您没有为数组分配正确的内存量,也没有为字符串分配正确的内存量。
  • 在第一次阅读循环后,您没有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;
}