What is the best practice for declaring large, global arrays in C? For example, I want to use myArray
throughout the application. However, I lose the use of sizeof() if I do this:
// file.c
char* myArray[] = { "str1", "str2", ... "str100" };
//file.h
extern char* myArray[];
// other_file.c
#include "file.h"
size_t num_elements = sizeof( myArray ); // Can determine size of incomplete type.
You could define the size:
// file.c
char *myArray[100] = { "str1", "str2", ... "str100" };
// file.h
extern char *myArray[100];
Then sizeof
should work, but you could also just #define
the size or set a variable.
Another options is to count up the length and store it one time in your code...
// file.c
char *myArray[] = { "str1", "str2", ... "strN", (char *) 0 };
int myArraySize = -1;
int getMyArraySize() {
if( myArraySize < 0 ) {
for( myArraySize = 0; myArray[myArraySize]; ++myArraySize );
}
return myArraySize;
}
// file.h
extern char *myArray[];
int getMyArraySize();
This would allow an unknown size at compile time. If the size is known at compile time just storing the constant will save the overhead of counting.
I think this is the solution you're looking for:
// file.c
char* myArray[] = { "str1", "str2", ... "str100" };
const size_t sizeof_myArray = sizeof myArray;
//file.h
extern char* myArray[];
extern const size_t sizeof_myArray;
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