Questions on usages of sizeof
Posted
by Appu
on Stack Overflow
See other posts from Stack Overflow
or by Appu
Published on 2010-03-29T05:39:09Z
Indexed on
2010/03/29
5:43 UTC
Read the original article
Hit count: 458
Question 1
I have a struct like,
struct foo
{
int a;
char c;
};
When I say sizeof(foo)
, i am getting 8
on my machine. As per my understanding, 4 bytes for int, 1 byte for char and 3 bytes for padding. Is that correct? Given a struct like the above, how will I find out how many bytes will be added as padding?
Question 2
I am aware that sizeof
can be used to calculate the size of an array. Mostly I have seen the usage like (foos
is an array of foo
)
sizeof(foos)/sizeof(*foos)
But I found that the following will also give same result.
sizeof(foos) / sizeof(foo)
Is there any difference in these two? Which one is preffered?
Question 3
Consider the following statement.
foo foos[] = {10,20,30};
When I do sizeof(foos) / sizeof(*foos)
, it gives 2. But the array has 3 elements. If I change the statement to
foo foos[] = {{10},{20},{30}};
it gives correct result 3. Why is this happening?
Any thoughts..
© Stack Overflow or respective owner