Setting an array to one value

If it's an array of byte values, or you want to set each byte to a specific value, you can use memset:

char xyzzy[100];
int plugh[40];
memset (xyzzy, 7, sizeof (xyzzy)); // all chars set to 7.
memset (plugh, 0x42, sizeof (plugh));  // all integers set to (e.g.) 0x42424242.

Another possibility is to create a template of the correct size at initialisation time (either real initialisation as per below, or in an init function), then call memcpy to blat (a) it onto the real array at a later date.

static int template[] = { 1, 1, 1, 1, 1 };
int zorkmid[3];
memcpy (zorkmid, template, sizeof (zorkmid)); // ensure template is at
                                              // least as big as zorkmid.

This latter method is also handy for populating structures with a fixed pre-calculated value: initialise a dummy copy with the required fields set then memcpy it instead of manually setting all the fields each time you want a new instance.


(a)Aside: etymology of blat:

The Jargon file (see the glossary for all the definitions) lists blat as either the four metasyntactic variable {foo, bar, thud, blat}, or a synonym for blast, sense 1.

In turn, blast (sense 1) is defined as a synonym of BLT (that's not the sandwich), which "referred to any large bit-field copy or move operation".


You can set it to the same value, but only to 0

How to initialize all members of an array to the same value?

initialize all elements to 0:

int myArray[10] = { 0 }; // all elements 0

There is an answer in that page for gcc as well.


If you're setting the array to all 0's, or if the array is an array of bytes, you can use memset

// Set myArray to all 0's
memset(myArray, 0, numberOfElementsInMyArray * sizeof(myArray[0]));

If you need to set it to something other than 0 in units larger than a byte (e.g. set an array of ints to 1's), then there is no standard function to do that -- you'll have to write your own for loop for that.

Tags:

C