Carla is my name
Carla is my name

Reputation: 149

Size of element of array C

Consider the line <type> array[SIZE_OF_ARRAY];. Later I need to use the size of an element of this array (ie for a fwrite). However I might change the <type> in future, so can't have a fixed size. The solution I found was to use sizeof(array[0]). While it works for my case, it doesn't feel very pretty, and it would run into problems if the array could be empty. Is there a better alternative?

Upvotes: 1

Views: 88

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311146

if the array could be empty. Is there a better alternative?

Array may not be empty. It can be uninitialized. Nevertheless this expression

sizeof(array[0])

is in any case valid because the operand is unevaluated expression in the sense that there is no access to the memory (though the expression itself can be evaluated at run time if array[0] is in turn a variable length array).

An alternative expression can look like

sizeof( *array )

You may use either expression with the same effect.

Upvotes: 3

Related Questions