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.
foo=sizeof(para)/sizeof(para[0]);
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 .
Using sizeof directly to find the size of arrays can result in an error in the code, as array parameters are treated as pointers.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With