Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C : static array

Tags:

arrays

c

I need to have a static void* array[1024]; in a library and i need to have it set to NULL for every entries.

My question is about the best way to set the entire array to NULL, is a memset (array, NULL, sizeof (void*) * 1024) the best solution?

like image 328
claf Avatar asked Feb 16 '09 12:02

claf


3 Answers

static pointers are automatically initialized to NULL. See C99:TC3 6.7.8, §10:

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:

  • if it has pointer type, it is initialized to a null pointer;
  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;
  • if it is an aggregate, every member is initialized (recursively) according to these rules;
  • if it is a union, the first named member is initialized (recursively) according to these rules.

Also, contrary to what others have written,

memset(array, 0, sizeof(array));

isn't guaranteed to result in null pointers. On some systems, a pointer with all its bits set to 0 might actually be valid. For mainstream systems, that's not the case, but with embedded systems, one never knows.

The safe way to set all entries to a null pointer is to either loop over the entries yourself and set them to NULL, or to use an uninitialized static array which you can memcpy() over the array you want to set to NULL.

like image 110
Christoph Avatar answered Oct 03 '22 12:10

Christoph


static void* array[1024] = {0};

or, as kmkaplan points out in the comment, just:

static void* array[1024];

although I prefer the first solution just to remind me that it's set to zeros (the compiler shouldn't generate any code for this unless it's brain-dead).

You don't need to memset it at all since file-level variables are initialized to zero anyway.

If you need to reset them to NULLs at some point after startup, use:

memset(array, 0, sizeof(array));

This works on most platforms (every one I've ever seen and that's quite a lot) since the null pointer is usually zero bits. But the standard doesn't guarantee this so, on those obscure platforms, it's safer to do:

for (i = 0; i < sizeof(array) / sizeof(void*); i++)
    array[i] = NULL;
like image 27
paxdiablo Avatar answered Oct 03 '22 11:10

paxdiablo


memset will do it in runtime.

static void* array[1024] = {0};

suggested by Pax will do it in compile time and it will increase the size of the executable.

For a library I believe memset is more appropriate.

like image 33
kgiannakakis Avatar answered Oct 03 '22 10:10

kgiannakakis