C语言入门课程中scanf格式匹配警告问题求助
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
%dformat specifier tellsscanfto read an integer value, and it needs a memory address (pointer) to store that integer—specifically a pointer to anint(int*). This is howscanfcan write the value it reads directly into your variable. - In your code, you wrote
(int)ph[i].vi.temperature: this takes thefloatvalue stored intemperature, converts it to an integer value, and passes that number toscanf. You're passing a raw integer instead of a pointer to wherescanfshould 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

