c - 在 C 中使用 fscanf,得到奇怪的输出

标签 c arrays file pointers scanf

我正在尝试使用 fscanf 读取一个文件,但它没有像我预期的那样工作。由于我是 C 的新手,问题可能出在我自己的理解上,但无论哪种方式,我都需要一些帮助。

我得到了一个具有流动结构的文件:

3
one word 7
flying horse 11
nice guy 7

第一行告诉我此行之后文件中存在多少行 其他行是 holdein 2 words 和 1 int,全部用空格分隔。 我正在尝试使用 fscanf 读取文件,我就是这样做的:

    // get number of lines
    int Number_of_objects_in_file;
    fscanf(MYFILE_File, "%d", &Number_of_objects_in_file);

    //creat 2 arrays to use
    char *Array_of_words[Number_of_objects_in_file][2];
    int *Array_of_int[Number_of_objects_in_file];

    //creat needed variables
    int x = 0;
    int g = Number_of_objects_in_file;

    //read all lines
    while (x < g){
        char *Temp1 = malloc(42*sizeof(char));
        char *Temp2 = malloc(42*sizeof(char));
        int *Temp3 = malloc(3*sizeof(int));
        fscanf(MYFILE_File,"%s %s %d",Temp1,Temp2,Temp3);
        Array_of_words[x][0] = Temp1;
        Array_of_words[x][1] = Temp2;
        Array_of_int[x] = Temp3;
        printf("name added: %s, 2:nd name added: %s and Array_of_int: %d \n",Array_of_words[x][0], Array_of_words[x][1], Array_of_int[x]);
        x++;
    }
fclose(Map_File);

打印语句正确地打印了名字,但是当我尝试打印 int 时,它没有给出正确的回答者,而是我打印了一个随机数 示例*(一行)*:

name added: one, 2:nd name added: word and Array_of_int: 463455

它应该是这样的:

name added: one, 2:nd name added: word and Array_of_int: 7

.我不知道我哪里做错了,希望你们能帮助我。

我正在使用 -std=c99 -Wall

最佳答案

发生这种情况是因为您将 Temp3 变量声明为 int* 而不是 int,这实际上是不需要的,因为您只需要读取单个值。然后,当您打印此变量时,它打印的是内存位置而不是读取的值。

要么将您的声明更改为 int 并停止 malloc() 处理此变量,要么改为打印 Temp3[0]

关于c - 在 C 中使用 fscanf,得到奇怪的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22438368/

相关文章:

c++ - 将 int 数组更改为 char 数组

file - 如何在 linux/unix 中使用排除列表压缩文件

C从文本文件中读取结构

c - 在 while(getchar() != '\n' ) 中用 fgetc 或 getc 替换 getchar;

c - 从 fgets() 输入中删除尾随换行符

php - 停止重复插入

javascript - 根据值更改的时间将数组拆分为更小的数组

将编码的音频文件转换为具有信号值的文本

c - 关于指针和C数组的问题

C:将文本文件读入结构数组