Assume that you have the struct my_struct in C.
Then you are using sizeof(my_struct) to find how many bytes that struct have. Is there any way to find out that my_struct is a struct just by using sizeof() method in C?
For example, if I want to find out that my_variable is 16-bit, then I just check if sizeof(my_variable) == 2.
Can I do the same for struct in C?
CodePudding user response:
Can I do the same for struct in C?
sizeof(my_variable) does the exact same thing for structs as for non-structs.
Specifically,
sizeof( my_variable ) == 2doesn't mean the variable uses up 16 bit.It means that my_variable uses up 2 bytes. Even though a byte is usually 8 bits in size these days, that's not always the case. Historically, they have been as large as 32 bits!
sizeof( my_variable ) == 2doesn't mean the variable can store 16-bit numbers.sizeofdoesn't say anything about the type except for its size.
For example,
sizeof( long ) sizeof( float ) and sizeof( struct { char a; int b; } ) could all return the same number.
