I need a big null array in C as a global. Is there any way to do this besides typing out
char ZEROARRAY[1024] = {0, 0, 0, /* ... 1021 more times... */ };
?
Global variables and static variables are automatically initialized to zero. If you have simply
char ZEROARRAY[1024];
at global scope it will be all zeros at runtime. But actually there is a shorthand syntax if you had a local array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. You could write:
char ZEROARRAY[1024] = {0};
The compiler would fill the unwritten entries with zeros. Alternatively you could use memset to initialize the array at program startup:
memset(ZEROARRAY, 0, 1024);
That would be useful if you had changed it and wanted to reset it back to all zeros.
character. it is a integer.{} discussion: stackoverflow.com/questions/17589533/… memset is not obviously correct: I think it only works for 0: stackoverflow.com/questions/11138188/…-Werror=missing-braces in gcc, it must be initialized to {{0}}. If the first struct element is an other struct then{{{0}}} and so on. See stackoverflow.com/questions/5434865/…int arr[256]={1,2,7,{0}}; ... which brought me here. Didn't even know this partial-zeroing was a thing until I saw it.If you'd like to initialize the array to values other than 0, with gcc you can do:
int array[1024] = { [ 0 ... 1023 ] = -1 };
This is a GNU extension of C99 Designated Initializers. In older GCC, you may need to use -std=gnu99 to compile your code.
... to denote a range is a gcc-specific extension.
charetc, but if you want an array-of-pointers, you should set them explicitly to NULL, there is (absurdly!) no guarantee that NULL is represented as zero-bytes. This even though the literal0implicitly represents the null pointer.