Let us say that I declare and initialize
int a[3] = {1, 2, 3};
How can I later asisgn the entire array in one fell swoop? i.e.
a = {3, 2, 1};
Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value. Until an array element is first assigned a value, it has a Null (empty) value.
If your c compiler supports compound literals, you can use memcpy
:
memcpy(a, (int[]){3, 2, 1}, sizeof a);
If you don't plan to stick any variables in there (you can; isn't C99 amazing?), (int[])
can be replaced by (const int[])
to put the literal into static memory.
compound literal is part of ANSI C (C99). Since it is part of the language, any compiler claiming to be conforming to C99 must support this:
memcpy(a, (int[]){3, 2, 1}, sizeof a);
gcc can be invoked as "gcc -Wall -W -std=c99 -pedantic" to specify the standard.
Since it is more than 11 years since C99, I think it's safe and probably a good idea to start using the new capabilities the language provides.
compound literals are discussed in section 6.5.2.5 of n869.txt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With