Phui Hock wrote:
Hi,
I'm a newbie in C. Can anyone tell me why the size of 'test' is 8
bytes instead of 4 bytes when I uncomment the 'struct list *next;'? I
hope someone can can explain to me.
Sure. A pointer is a variable, so it has a size in bytes. What did you
expect ?
I would say that pointers are probably 4 bytes long on your platform,
but they also may be shorter and your compiler has added extra padding bits.
Take care, the size of struct may not equal the total of it's members
sizes.
I can't find answer anywhere in my
references nor on the net. Thank you very much.
#include <stdint.h>
typedef struct list{
uint8_t a :6;
uint8_t b :1;
uint8_t c :1;
struct {
uint8_t x :4;
uint8_t y :1;
uint8_t z :3;
} inner;
/* struct list *next; */
} test;
int main(){
it's int main(void) or int main(int argc, char **argv)
printf("size of test is %d\n", sizeof(test));
call of printf() without definition
(hint : you need to #include <stdio.h>)
return 0;
}
[laotseu@localhost dev]$ gcc -Wall -ansi -pedantic -obytes bytes.c
bytes.c:9: warning: bit-field `x' type invalid in ISO C
bytes.c:10: warning: bit-field `y' type invalid in ISO C
bytes.c:11: warning: bit-field `z' type invalid in ISO C
bytes.c:5: warning: bit-field `a' type invalid in ISO C
bytes.c:6: warning: bit-field `b' type invalid in ISO C
bytes.c:7: warning: bit-field `c' type invalid in ISO C
Woops. Non portable code ?
With line 13 commented out :
[laotseu@localhost dev]$ ./bytes
size of test is 2
With line 13 uncommented :
[laotseu@localhost dev]$ ./bytes
size of test is 8
Did I say something about padding ?-)
(NB : pointers are 4 bytes long on my platform.)
Bruno