Now It is showing '4' as a result. I think it should display 5040 right?
No, you're wrong. Check the data types.
First of all, a little about sizeof
operator, from C11
, chapter §6.5.3.4
The sizeof
operator yields the size (in bytes) of its operand, which may be an
expression or the parenthesized name of a type. The size is determined from the type of
the operand. [...]
bus
is a pointer, so, sizeof(bus)
is the same as sizeof (struct busData*)
, which is the size of a pointer, which depending on your environment, can give you the result, of which, the common nones are 4 or 8.
After that, there can be padding in between structure elements and at the end, so a structure defined like
struct busData{
int busNum;
char str[SIZE+1]; //SIZE = 1000
};
defining a variable of that type and trying to check the size via sizeof
may not give you (4+1000+1) == 1005
bytes, for most of the environments.
Quoting again,
[....] When
applied to an operand that has structure or union type, the result is the total number of
bytes in such an object, including internal and trailing padding.
So, you need to account for padding also.
That said,
printf("\n%d", sizeof(bus));
actually causes undefined behavior. You need to write
printf("\n%zu", sizeof(bus));
as sizeof
yields a result of type size_t
.