C Programming - Structures, Unions, Enums - Discussion

Discussion Forum : Structures, Unions, Enums - Point Out Errors (Q.No. 3)
3.
Point out the error in the program?
#include<stdio.h>

int main()
{
    struct a
    {
        float category:5;
        char scheme:4;
    };
    printf("size=%d", sizeof(struct a));
    return 0;
}
Error: invalid structure member in printf
Error in this float category:5; statement
No error
None of above
Answer: Option
Explanation:

Bit field type must be signed int or unsigned int.

The char type: char scheme:4; is also a valid statement.

Discussion:
25 comments Page 2 of 3.

Ritesh_IIIT said:   1 decade ago
@Prashant O_O: Friend I ran this code on gcc compiler after making few changes, here is my code:

#include<stdio.h>

int main()
{
struct a
{
int category:5;
char scheme:4;
};

printf("size=%d", sizeof(struct a));
return 0;
}

And according to your suggestion output must be 9 but it is 8 even take any values in the bit field still the output will be 8. Can you please explain me this.

Professor_x said:   1 decade ago
You can test this.

The minimum size of a structure variable will be the size of the biggest data type in the structure.

i.e.,

In this example (*replace float with int).

sizeof (struct a) will be a minimum of 4 in 32-bit turboc.

Please correct me if I'm wrong.

Monisha said:   1 decade ago
What is bit field? explain it in detail.

Prema said:   1 decade ago
What is the purpose of reserving the bits for a variable?

As the size of integer is 2 bytes or 4 bytes depending on the compiler why we should reserve 5 bits in this code?

Chaitu said:   1 decade ago
@Prema.

The main purpose of reserving bits in declaring them is the memory allocation for the variables can be used for what we want.

So by allocating required number of bits, we can save the memory.

Rahul said:   1 decade ago
What is signed int or unsigned int?

Priya said:   1 decade ago
What is the use of number after category:5 and scheme:4?

Sudha said:   1 decade ago
Nice explanation friends. Thanks.

Chinni said:   9 years ago
@Professor_X.

You said that sizeof struc is the biggest datatype.

Then what is the size if UNION?

Vishalakshi said:   9 years ago
@Professor_X.

As you said, The minimum size of a structure variable will be the size of the biggest data type in the structure.

This sentence is valid only for union not structure because the structure will allocate different memory for different data types. But union allocates memory for the largest data type.

Please correct if I'm wrong. Thank you.


Post your comments here:

Your comments will be displayed after verification.