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

时间:2014-03-16 14:49:14

标签: c arrays file pointers scanf

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

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

3
one word 7
flying horse 11
nice guy 7

第一行告诉我文件中存在多少行 其他行是holdein 2个单词和一个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);

print语句正确打印名称,但是当我尝试打印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

1 个答案:

答案 0 :(得分:2)

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

将声明更改为int并停止malloc()此变量或改为打印Temp3[0]