Satya Kumar
Satya Kumar

Reputation: 177

how to set values in bitfield set variables in a structure?

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?

Upvotes: 0

Views: 2229

Answers (2)

unwind
unwind

Reputation: 399833

There are a few problems with your code:

  1. A 1-bit signed integer isn't very useful, it can only hold the values -1 and 0.
  2. You can't have a pointer to a bit-field, that's not what pointers mean.
  3. Also, there's nothing in the %d specifier that tells the scanf() 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.

Upvotes: 2

urzeit
urzeit

Reputation: 2909

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.

Upvotes: 1

Related Questions