Are there scenarios where there can be a difference between sizeof(struct structure_name) and sizeof(object) where object is of type struct structure_name in C?
2 Answers
No there is no difference between sizeof(type) and sizeof(o) where the declared type of o is type.
There can be differences if the declared type of the object isn't truly representative of the object. For example
char arrayValue[100];
sizeof(arrayValue); // 100 on most systems
char* pointerValue = arrayValue;
sizeof(pointerValue); // 4 on most 32 bit systems
This difference occurs because sizeof is a compile time construct in C. Hence there is no runtime analysis and the compiler looks instead at the statically declared types.
2 Comments
char *x is a very different type from char y[100], even though in many cases, an expression involving y ends up as a char *. Of course, one of the exceptions is sizeof; sizeof(x) != sizeof(y) on any plausible system (although theoretically the size of a pointer could be 100 bytes, it is pretty unlikely to be a problem in any of our lifetimes).sizeof on values.No; sizeof(type) and sizeof(object-of-type) produce the same result at all times.
Well, there's a caveat that with a VLA (variable-length array), the sizeof() might be a run-time operation, but otherwise, they are fixed. And you can make a case that even with a VLA, the result of sizeof(variably-qualified-type) and sizeof(object-of-same-variably-qualified-type) will produce the same result, so VLAs are not really an exception.
6 Comments
sizeof be a run-time operation?sizeof() can be a run-time operation: void minimal(int n) { int array[n]; printf("%zu\n", sizeof(array)); ... }sizeof(struct NAME *) and sizeof(struct NAME)?