gpt4 book ai didi

c - 为什么它在 'c ' 中打印 null

转载 作者:行者123 更新时间:2023-11-30 21:01:18 25 4
gpt4 key购买 nike

我得到一个包含元素周期表的文件,并将其放入函数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;
}

最佳答案

您的代码存在多个问题:

  • 您为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;
}

关于c - 为什么它在 'c ' 中打印 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36104415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com