4

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 2

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

A 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).
@JonathanLeffler I agree they are very different types. The OP appears new to C and i wanted to illustrate what I thought was one of the more common pitfalls when developers start using sizeof on values.
3

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

Really, can sizeof be a run-time operation?
In C99, yes: sizeof() can be a run-time operation: void minimal(int n) { int array[n]; printf("%zu\n", sizeof(array)); ... }
@JonathanLeffler that's interesting. Didn't think that was allowed
@JonathanLeffler Very interesting. Even I didn't think that was allowed, but it is allowed.
@JonathanLeffler on this note, what's the difference btw sizeof(struct NAME *) and sizeof(struct NAME)?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.