You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言中scanf为何要求传入指针?代码格式警告解析

TI-RSLK状态机代码scanf编译警告问题解决

问题描述

我编写了实现TI-RSLK状态机的C语言代码,在main函数中使用scanf("%u \n", input)语句时触发编译警告,提示格式符%u期望unsigned int *类型参数,但传入的是unsigned int类型变量。我原以为%u接收无符号整数、%d接收整数,改用%d后仍提示需传入指针类型。

原代码

#include <stdio.h>
struct state{
    unsigned int output;
    unsigned int delay;
    const struct state *next[4];
};

#define center &fsm[0]
#define left &fsm[1]
#define right &fsm[2]

typedef const struct state state_t;

state_t fsm[3] = {
    {3, 50, {right, left, right, center}},
    {2, 50, {left, center, right, center}},
    {1, 50, {right, left, center, center}}
};

int main(void)
{
    state_t *spt; 
    unsigned int input;
    unsigned int output;
    spt = center;
    while(1) {
        output = spt->output;
        printf("%u \n", output);  
        scanf("%u \n", input);
        spt = spt->next[input]; 
    }
    printf("Hello World");

    return 0;
}

编译警告信息

main.c: In function ‘main’:
main.c:37:17: warning: format ‘%u’ expects argument of type ‘unsigned int *’, but argument 2 has type ‘unsigned int’ [-Wformat=]
   37 |         scanf("%u \n", input);
      |                ~^      ~~~~~
      |                 |      |
      |                 |      unsigned int
      |                 unsigned int *
3 

解决方法

  1. 核心问题:scanf的参数要求
    scanf是通过指针修改变量值的,不管使用%u还是%d格式符,都需要传入变量的地址(指针类型),而不是变量本身。因此要给input加上取地址符&。
  2. 格式串优化
    格式串里的\n完全没必要,scanf会自动忽略输入中的空白字符(包括换行、空格),保留\n会导致程序等待额外的输入结束信号,影响交互逻辑。

修改后的scanf语句应为:

scanf("%u", &input);

修改后的完整main函数

int main(void)
{
    state_t *spt; 
    unsigned int input;
    unsigned int output;
    spt = center;
    while(1) {
        output = spt->output;
        printf("%u \n", output);  
        scanf("%u", &input);
        spt = spt->next[input]; 
    }
    printf("Hello World");

    return 0;
}

内容的提问来源于stack exchange,提问作者user2874626

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 20:45:35