Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Result of 'sizeof' on array of structs in C?

In C, I have an array of structs defined like:

struct D {     char *a;     char *b;     char *c; };  static struct D a[] = {     {         "1a",         "1b",         "1c"     },     {         "2a",         "2b",         "2c"     } }; 

I would like to determine the number of elements in the array, but sizeof(a) returns an incorrect result: 48, not 2. Am I doing something wrong, or is sizeof simply unreliable here? If it matters I'm compiling with GCC 4.4.

like image 815
Joseph Piché Avatar asked Dec 14 '09 02:12

Joseph Piché


People also ask

How do you get the size of a structure array?

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

What does sizeof array return in C?

sizeof() Operator to Determine the Size of an Array in C It returns the size of a variable. The sizeof() operator gives the size in the unit of byte. The sizeof() operator is used for any data type such as primitives like int , float , char , and also non-primitives data type as an array , struct .

Can you use sizeof on an array in C?

Using sizeof directly to find the size of arrays can result in an error in the code, as array parameters are treated as pointers.

Does sizeof return array size?

The sizeof() operator returns pointer size instead of array size. The 'sizeof' operator returns size of a pointer, not of an array, when the array was passed by value to a function.


1 Answers

sizeof gives you the size in bytes, not the number of elements. As Alok says, to get the number of elements, divide the size in bytes of the array by the size in bytes of one element. The correct C idiom is:

sizeof a / sizeof a[0] 
like image 187
Grandpa Avatar answered Sep 17 '22 12:09

Grandpa