how to zero a mixed data type array?

09 Jul 2013

I need to zero a mixed data type array and am wondering if there is a better way. The code below does work but seems nonelegant at best. Anyone have a cleaner way??

struct preset_data {
    char *pref;
    char *name;
    short int lat, lon;
};

preset_data preset_table[] = {                  // my array has a total of 10 entries...
    {"","",0,0},
    {"","",0,0},
    {"","",0,0},
    {"","",0,0},
    {"","",0,0},
    {"","",0,0},
    {"","",0,0},
    {"","",0,0},
    {"","",0,0},
    {"","",0,0},
};

09 Jul 2013

You could create a variable of type "const struct preset_data" predefined with the appropriate values then use memcpy() to copy it into each element of the array.

Or you could simply use:

memset(preset_data, 0, sizeof(preset_data));

to fill ever byte of the array with zeros. But this is problematical as it makes assumptions about the data in the structure.

10 Jul 2013

The problem is that you are not initializing it to zero - a pointer to an empty string isn't the same as a NULL pointer! So memset won't do the right thing either.

Note that if you DID want to zero-initialize everything (including the pointers), you could just do

preset_data preset_table[10] = {};

because in C++ (but not in C) an empty initialization list will zero-initialize.

What is wrong with the code that you have already? I don't think there is a shorter way to write it and still allow static initialization. The only alternative I can think of is to initialize it at runtime using a loop.

10 Jul 2013

The code in your example does NOT set the array to zero (the memset DOES set it to zero) ,but initialises the pointers to point to the constant empty string "". Furthermore a file-level (global) array will be initialised to zero by the startup code. So: preset_data preset_table[10]; will actually define an all zero array.