Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare global array of size defined in another file in C99?

Tags:

arrays

c

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.

like image 461
davhak Avatar asked Nov 05 '22 05:11

davhak


1 Answers

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.

like image 69
Martin v. Löwis Avatar answered Nov 09 '22 10:11

Martin v. Löwis