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

C语言入门课程中scanf格式匹配警告问题求助

Understanding Your scanf Warning in C

Hey there! Let's break down this warning you're encountering—it's a super common gotcha when working with input functions like scanf in C, so you're definitely not alone here.

Why the Warning Happens

First, let's parse the warning message clearly:

warning: format '%d' expects argument of type 'int *', but argument 2 has type 'int'

Here's the core issue:

  • The %d format specifier tells scanf to read an integer value, and it needs a memory address (pointer) to store that integer—specifically a pointer to an int (int*). This is how scanf can write the value it reads directly into your variable.
  • In your code, you wrote (int)ph[i].vi.temperature: this takes the float value stored in temperature, converts it to an integer value, and passes that number to scanf. You're passing a raw integer instead of a pointer to where scanf should write the input. That's a total type mismatch, hence the warning.

On top of that, your temperature variable is a float (from the vitalInformation struct), but you're using %d (for integers)—that's another misalignment contributing to the problem.

Fixing the Warning

You have two main options depending on what you want to achieve:

Option 1: Read a floating-point value directly into temperature

If you want to read a decimal number (like 36.8) into the float temperature variable, use the %f format specifier and pass the address of the variable with &:

// Use %f for float, and & to get the variable's memory address
while (scanf("%f", &ph[i].vi.temperature) == 1) {
    // Your logic here
}

This matches the type perfectly: &ph[i].vi.temperature is a float*, which pairs correctly with %f.

Option 2: Read an integer, then convert it to float

If you intend to read an integer (like 37) and store it as a float in temperature, use a temporary integer variable to handle the input first:

int temp_int;
// %d matches with &temp_int (an int*)
while (scanf("%d", &temp_int) == 1) {
    // Convert the integer to float and assign to temperature
    ph[i].vi.temperature = (float)temp_int;
    // Your logic here
}

This keeps the scanf argument types aligned, eliminating the warning entirely.

A Critical Note About That Cast

Never use (int) (or any cast) to try to "fix" the pointer type here. Casting ph[i].vi.temperature to int just converts its current value to an integer, which scanf will treat as a memory address—this leads to undefined behavior (like crashing your program or corrupting memory) because you're writing to a random, invalid location.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:11:59