In C99 you can do it using a compound literal in combination with memcpy
memcpy(myarray, (int[]) { 1, 2, 3, 4 }, sizeof myarray);
(assuming that the size of the source and the size of the target is the same).
In C89/90 you can emulate that by declaring an additional "source" array
const int SOURCE[SIZE] = { 1, 2, 3, 4 }; /* maybe `static`? */
int myArray[SIZE];
...
memcpy(myarray, SOURCE, sizeof myarray);
Answer from AnT stands with Russia on Stack OverflowDeclaring and initializing arrays in C - Stack Overflow
Proper way of initialize an array
Initializing an array and then filling it with data
Initializing a variable sized array?
In C99 you can do it using a compound literal in combination with memcpy
memcpy(myarray, (int[]) { 1, 2, 3, 4 }, sizeof myarray);
(assuming that the size of the source and the size of the target is the same).
In C89/90 you can emulate that by declaring an additional "source" array
const int SOURCE[SIZE] = { 1, 2, 3, 4 }; /* maybe `static`? */
int myArray[SIZE];
...
memcpy(myarray, SOURCE, sizeof myarray);
No, you can't set them to arbitrary values in one statement (unless done as part of the declaration).
You can either do it with code, something like:
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 27;
:
myArray[99] = -7;
or (if there's a formula):
for (int i = 0; i < 100; i++) myArray[i] = i + 1;
The other possibility is to keep around some templates that are set at declaration time and use them to initialise your array, something like:
static const int onceArr[] = { 0, 1, 2, 3, 4,..., 99};
static const int twiceArr[] = { 0, 2, 4, 6, 8,...,198};
:
int myArray[7];
:
memcpy (myArray, twiceArr, sizeof (myArray));
This has the advantage of (most likely) being faster and allows you to create smaller arrays than the templates. I've used this method in situations where I have to re-initialise an array fast but to a specific state (if the state were all zeros, I would just use memset).
You can even localise it to an initialisation function:
void initMyArray (int *arr, size_t sz) {
static const int template[] = {2, 3, 5, 7, 11, 13, 17, 19, 21, ..., 9973};
memcpy (arr, template, sz);
}
:
int myArray[100];
initMyArray (myArray, sizeof(myArray));
The static array will (almost certainly) be created at compile time so there will be no run-time cost for that, and the memcpy should be blindingly fast, likely faster than 1,229 assignment statements but very definitely less typing on your part :-).
Lets say i wanna initialize an array of zeros.
Of course, one could do:
I)
int a[20];
for(int i = 0 ; i < 20; i++) { a[i]=0}
or, one could initialize one element, and the rest would be initialized to zero implicited
II)
int a[20] = {0};
i also found that you can skip the zero :
III)
int a[20] = {};
So, my question is, would the latter (II and III) be considered good practice?