Because the C/C++ standard does not allow to access the members of a bitfield via a pointer and you have to pass scanf a pointer.
how to set values in bitfield set variables in a structure?
-
30-05-2022 - |
Question
I have written the code below on Qt,when I put values in it it program.exe stops working.
struct aim
{
int i : 1;
int j : 1;
};
int main()
{
aim missed;
printf("Enter value of i :: ");
scanf("%u",missed.i);
printf("Enter value of j :: ");
scanf("%u",missed.j);
}
can anyone help me out with this problem?
Solution 2
OTHER TIPS
There are a few problems with your code:
- A 1-bit signed integer isn't very useful, it can only hold the values -1 and 0.
- You can't have a pointer to a bit-field, that's not what pointers mean.
- Also, there's nothing in the
%d
specifier that tells thescanf()
function that the target value is a bit field (nor is there any other%
specifier that can do this, see 2).
The solution is to scanf()
to a temporary variable, range-check the received value, then store it in the bit field.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow