Declare a large global array

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. 
+6
source share
5 answers

You can determine the size:

 // file.c char *myArray[100] = { "str1", "str2", ... "str100" }; // file.h extern char *myArray[100]; 

Then sizeof should work, but you can also just #define specify the size or set the variable.

Other options are to count the length and save it once 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 give an unknown size at compile time. If the size is known at compile time, just saving a constant will save the overhead of counting.

+4
source

In C, you need to save the size separately (possibly in a structure with an array).

An array is nothing more than a memory block in C, it does not know how many elements are in the array, and, in addition, looking at the type of pointer, it does not even know the size of one element in the array * .

If you really want to use a global array, I would recommend something like this:

 #define ARRAY_SIZE 1000 char* myArray[ARRAY_SIZE] = {....}; 

* As some people have noted, this is not entirely true, but (but still a good rule for the imho program).

+2
source

I think this is the solution you are 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; 
+1
source

It depends on whether it is a static or dynamic array. Only if it is a static array, you can use sizeof() .

 #define MAX_ELE (100) const static char* MyArray[] = {"str1","str2",....,"str100"} 
0
source

In file.h you can put:

 #include <stddef.h> extern char *myArray[]; extern const size_t myArray_len; 

Then in file.c you have:

 #include "file.h" char *myArray[] = { "str1", "str2", ... "str100" }; const size_t myArray_len = sizeof myArray / sizeof myArray[0]; 

That way, your other modules can reference myArray_len , and you don't need to explicitly specify the size of the array anywhere.

(The disadvantage is that myArray_len is just a const -qualified variable, not a constant expression, which means you cannot use it to perform operations such as initializing objects with a static storage duration or sizing unchanged arrays).

0
source

Source: https://habr.com/ru/post/891605/


All Articles