Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof() structures not known. Why?

Tags:

Why can't I use sizeof() on simple structs?

eg:

private struct FloatShortPair {     public float myFloat;     public short myShort; };  int size = sizeof(FloatShortPair);  //CS0233 

error CS0233: 'FloatShortPair' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)

MSDN states:

The sizeof operator can only be used for types that are compile-time constants. If you are getting this error, make sure that the size of the identifier can be determined at compile time. If it cannot, then use SizeOf instead of sizeof.

How are float and short not compile time constants? 8-/

like image 314
GazTheDestroyer Avatar asked Nov 08 '11 09:11

GazTheDestroyer


People also ask

Does sizeof work on struct?

The sizeof for a struct is not always equal to the sum of sizeof of each individual member. This is because of the padding added by the compiler to avoid alignment issues. Padding is only added when a structure member is followed by a member with a larger size or at the end of the structure.

How can the size of a structure be determined?

In C language, sizeof() operator is used to calculate the size of structure, variables, pointers or data types, data types could be pre-defined or user-defined. Using the sizeof() operator we can calculate the size of the structure straightforward to pass it as a parameter.

What does sizeof return for struct?

If an unsized array is the last element of a structure, the sizeof operator returns the size of the structure without the array.

What is the relationship between the result of sizeof () for a structure variable and the sum of the sizeof () calls across the same structure's members?

The result of the sizeof operand applied to a structure object can be equal to the sum of sizeof applied to each member separately.


1 Answers

The sizes of short and float are constant - but how the CLR decided to pack that float in memory isn't necessarily constant. For example, on a 64-bit processor it may decide to align each value on an 8-byte boundary.

From the C# 4 spec, section 18.5.8:

For certain predefined types, the sizeof operator yields a constant value as shown in the table below.

[...]

For all other types, the result of the sizeof operator is implementation-defined and is classified as a value, not a constant.

[...]

For alignment purposes, there may be unnamed padding at the beginning of a struct, within a struct, and at the end of a struct.

Note that you can use sizeof in this situation, within an unsafe context. Whether you should use that or Marshal.SizeOf depends on what you're trying to do.

like image 74
Jon Skeet Avatar answered Sep 19 '22 14:09

Jon Skeet