【问题标题】:Warning: Variable is unitialized in this function警告:此函数中的变量未初始化
【发布时间】:2015-02-16 22:03:35
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "scanner.h"

int WhatFell(char *typeoffood)
{
    if (strcmp(typeoffood,"meat") == 0);
    return 1;
}

void getData(char *typeoffood)
{
    printf("What fell on the floor? ");
    typeoffood = readToken(stdin);
    return;
}

int main(int argc, char **argv)
{
    char *typeoffood;
    int x;
    getData(typeoffood);
    x = WhatFell(typeoffood);
    printf("%s\n",typeoffood);
    printf("%d\n",x);
    return 0;
}
eat.c: In function ‘main’:
eat.c:14:12: warning: ‘typeoffood’ is used uninitialized in this function [-Wuninitialized]
getData(typeoffood);
^

一些注意事项:

'readToken' 在 "scanner.h" 包含中找到,它只是用于字符串的 scanf() 的安全版本。 另外请只关注错误,这只是我编写的代码的 sn-p,如果我能够在我的程序中使用函数 getData 进行字符串输入。

我正在尝试使用一个函数来询问用户字符串输入(我可以使用整数/实数很好地完成),然后使用该字符串来运行另一个函数,但是我不断收到所有这些奇怪的警告,如果我运行它我得到一个分段错误。

【问题讨论】:

  • typeoffood = readToken(stdin); 对getData 的调用者没有任何意义。该变量是按值传递的。
  • 请注意,由于if 后面的分号,此函数int WhatFell(char *typeoffood) { if (strcmp(typeoffood,"meat") == 0); return 1; } 无法正常工作。删除虚假分号,它并不总是返回值,这是一个不同的问题。

标签: c initialization compiler-warnings


【解决方案1】:
char *typeoffood;
int x;
getData(typeoffood);

typeoffood 未初始化,而是传递给getData(),因此会收到未初始化的数据。注意:消息中的数字 12:14 告诉您与错误相关的行号。

您应该将typeoffood 作为指向指针的指针传递:

getData(&typeoffood);

并给getData()原型:

void getData(char **);

【讨论】:

  • 好的,谢谢!我得到了它。我知道它必须是带有指针和地址的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-24
  • 2021-12-06
  • 1970-01-01
  • 1970-01-01
  • 2021-04-15
  • 1970-01-01
相关资源
最近更新 更多