Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare large global array

Tags:

arrays

c

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.
like image 756
Lang Jas Avatar asked Jun 29 '11 00:06

Lang Jas


2 Answers

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.

like image 178
LavaSlider Avatar answered Oct 30 '22 03:10

LavaSlider


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;
like image 42
R.. GitHub STOP HELPING ICE Avatar answered Oct 30 '22 04:10

R.. GitHub STOP HELPING ICE