Taking into account the VLA (variable length array) I would like to ask your opinions on the following problem: If an array is defined at global scope in one file:
int arr[] = {1, 2, 3};
// in the same file it is no problem to obtain the number of elements in arr by
#define arr_num sizeof(arr)/sizeof(arr[0])
// or
enum {arr_num = sizeof(arr)/sizeof(arr[0])};
The problem is that in other files in the same project I would like to create other arrays again at global scope with the same number of elements as there are in arr. But how can one achieve this in C99 if there is no way to 'extern' the enum or #define. Of course one can #define the number of elements of arr by hand in a header file and later use it in the other files but this is very inconvenient since by changing the number of elements in the array arr one has also to change by hand the value of this #define (this is even more inconvenient when arr is an array of structs).
Thanks very much for any help.
VLAs don't help with that: they need to be automatic variables, and hence you can't make a global variable a VLA. I agree with valdo that having a global variable containing the array size (or alternatively a function returning it) is the right approach.
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