Is there an easier way in C
to set an array to one value than using a for
loop and going setting each value one by one?
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 int
s to 1's), then there is no standard function to do that -- you'll have to write your own for loop for that.
Depends on the value. If it's zero, use memset(a, 0, sizeof(a))
. Otherwise, if it's a char array you can use memset with some other value. But memset always works at the char level so if your array is not char only zero is likely to be meaningful.
This is an old questions, but here are my two cents.
I guess that the computer has to iterate over each and every value one way or the other. So why not use a for-loop within a macro? This way your code does not clutter and you get something like a function.
For stack-allocated arrays (with compile-time defined size):
#define fill_array(array, value) \
for(int i; i < sizeof(array)/sizeof(array[0]); i++) \
{array[i]=value;}
For heap-alllocated arrays (iter is a pointer to the first entry of the array):
#define fill_array(iter, length, value) \
for(int i; i < length; i++) \
{*iter=value; iter++;}