Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

size of array of structs in bytes

Tags:

c#

i have an array of structs and i need to get the size of it in bytes

in C++ i can make it using sizeof()

but i need it C#

thnx

like image 461
Islam Muntasser Avatar asked Apr 13 '11 21:04

Islam Muntasser


People also ask

How do you get the size of an array of a struct?

foo=sizeof(para)/sizeof(para[0]);

How big can a byte array be?

The results show the maximum size is 2,147,483,645. The same behavior can be observed for byte, boolean, long, and other data types in the array, and the results are the same.

How do I get the size of an array of structures in CPP?

We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);


2 Answers

Marshal.SizeOf(typeof(MyStruct)) * array.Length

like image 200
user541686 Avatar answered Sep 22 '22 11:09

user541686


There is the sizeof operator. However, it can only be used in unsafe context.

There is also a difference to the method proposed in the other answer, namingly:

For all other types, including structs, the sizeof operator can be used only in unsafe code blocks. Although you can use the Marshal.SizeOf method, the value returned by this method is not always the same as the value returned by sizeof. Marshal.SizeOf returns the size after the type has been marshaled, whereas sizeof returns the size as it has been allocated by the common language runtime, including any padding.

source

Example:

unsafe
{
  int size = sizeof(MyStruct)*myArray.Length;
}
like image 20
Femaref Avatar answered Sep 19 '22 11:09

Femaref