【问题标题】:C: fscanf causes an uninitalized variable errorC: fscanf 导致未初始化的变量错误
【发布时间】:2013-09-10 20:03:51
【问题描述】:

我正在尝试从snack.dat 文件中调入信息,但收到此错误。

警告:“fido_speed”可能在此函数中使用未初始化[-Wuninitialized]|

其余的 int* 声明依此类推。

“Snack.dat”

10 20 5 15
19 20 20 20
1 50 1 51
10 20 10 20
0 0 0 0

代码

int main()
{
    FILE* input;
    FILE* output;

    const char* in_file="snack.dat";
    const char* out_file="snack.out";

    int* fido_speed;
    int* joe_speed;

    int* fido_distance;
    int* joe_distance;

    input = fopen(in_file,"r");
    output = fopen(out_file,"w");

    while(!feof(input)){

       fscanf(input,"%d %d %d %d", joe_distance, fido_distance, joe_speed, fido_speed);

        if (((*joe_distance)/(*joe_speed)) < ((*fido_distance)/(*fido_speed))){
            fprintf(output,"Fido is no longer hungry.");
        }

        else if(((*joe_distance)/(*joe_speed)) > ((*fido_distance)/(*fido_speed))){
            fprintf(output,"Joe makes it.");
        }

        else{
            fprintf(output,"/0");
        }
    };

    fclose(input);
    fclose(output);
    return 0;
}

【问题讨论】:

    标签: c file io scanf


    【解决方案1】:

    哎呀!您的指针没有分配任何存储空间(因此“未初始化”):

    int* fido_speed;
    

    是一个指针,它保存int 类型的地址(或者,如果未初始化,则为垃圾/虚假地址)。但是,它不保存它指向的 int 的值。为此,您需要 malloc() 它一些内存,或者将其指向现有的 int。

    在这种情况下,将普通 int 的地址传递给 scanf 可能更容易:

    int fido_speed;  // not a pointer
    fscanf(input, "%d", &fido_speed);
    

    【讨论】:

      【解决方案2】:

      错误信息非常明显:您使用的是未初始化的指针,因此您正在将数据读入内存的随机部分。您应该使用int 变量而不是int* 存储并使用&amp; 获取指向它们的指针。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-24
        • 2016-09-03
        相关资源
        最近更新 更多