使用scanf修复一些警告

时间:2014-03-09 17:57:03

标签: c warnings scanf

int stringCheck(char*);

void compile(int *instructionSet2, int *accumulator2, int *instructionCounter2, int *instructionRegister2, int *operationCode2, int *operand2)
{

    char *readIn;
    readIn = (char*)malloc(sizeof(char)*11);

    while(fgets(readIn,11,stdin) != NULL)
    {
        *instructionCounter2 = scanf("%d",(int*)readIn);
        instructionSet2[*instructionCounter2] = (stringCheck((char*)scanf("%s",readIn)));
        instructionSet2[*instructionCounter2] += (scanf("%d",(int*)readIn));
    }
}

int stringCheck(char *stIn)
{
    if (strcmp(stIn,"READ") == 0)
    {
        return 10 * 100;
    } /* Snipped to just give an idea of the numeric value assignment for words read. */
}

好吧,我在这里要做的是弄清楚如何正确阅读这样的一组指令:

00 READ 9
01 READ 10
02 LOAD 9
03 SUB 10
04 BRNG 7
05 WRIT 9
06 HALT 99
07 WRIT 10
08 HALT 99
09 SET 0
10 SET 0

我试图阅读这些文字时,我已经陷入了困境。基本上,我只想扫描一个int,一个字符串,然后另一个int,并在未到达文件末尾时继续执行此操作。

事实证明,scanf返回成功读取的字符数而不是指针,因此while循环中的第二行在编译时会警告我。

我正在尝试特别修复此警告:

virtualcomp.c:66:56: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]

具体指向此行:

instructionSet2[*instructionCounter2] = (stringCheck((char*)scanf("%s",readIn)));

我该如何解决这个问题?

注意:我试图避免输入更多变量,只使用现有变量。

2 个答案:

答案 0 :(得分:0)

您可以通过一次scanf调用解析所有三个变量。注意scanf返回分配的输入变量数。我想你需要这样的东西:

int n1, n2;
char buf[12];
...
...
sscanf(readIn, "%d %s %d",&n1, buff, &n2);

*instructionCounter2 = n1;
instructionSet2[*instructionCounter2] = stringCheck(buff);
instructionSet2[*instructionCounter2] += n2;

答案 1 :(得分:0)

尝试将int放入通用缓冲区(大小为11)是非正统的。

char *readIn;
readIn = (char*)malloc(sizeof(char)*11);
...
*instructionCounter2 = scanf("%d",(int*)readIn);

建议改为放弃malloc()并直接阅读2 int

char s[11];
char readIn[21 + sizeof s + 21 + 2];  // 21 is chars in a 64-bit int
while(fgets(readIn, sizeof readIn, stdin) != NULL)
{
   int n;
   if (sscanf(readIn, "%d%n", instructionCounter2, &n) != 1 || 
       sscanf(&readIn[n], "%11s%d",s,&instructionSet2[*instructionCounter2] != 2)
     Handle_SyntaxError();
   instructionSet2[*instructionCounter2] += stringCheck(s);
}

注意:更强大的解决方案会在用作数组索引之前评估instructionCounter2的值。