Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning an entire array with a single statement

Tags:

c

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};
like image 414
Mawg says reinstate Monica Avatar asked Dec 05 '11 02:12

Mawg says reinstate Monica


People also ask

How do you assign a value to each element in an array?

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.


2 Answers

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.

like image 146
Dave Avatar answered Oct 08 '22 00:10

Dave


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

like image 44
Karthik Gurusamy Avatar answered Oct 08 '22 01:10

Karthik Gurusamy