0

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?

Satya Kumar
  • 179
  • 1
  • 4
  • 19

2 Answers2

2

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.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • Additional remark: A pointer so a bitfield member would not even be possible at all because pointers are holding byte-adresses and bitfield members may have "fractional-byte" adresses. – urzeit May 30 '13 at 10:17
1

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.

urzeit
  • 2,863
  • 20
  • 36
  • then what should I use in place of scanf – Satya Kumar May 30 '13 at 10:05
  • To read a variable into a c bitfield I think you have to save it in a temporary variable you can get a pointer to and then copy it to the bitfield (and check if the value is valid for it) – urzeit May 30 '13 at 10:14