Alex Rivera | Logout

Assigning an entire array with a single statement

Asked 2011-12-05T02:20:24.550
12

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};
c
Edit
Report

2 Answers

15

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.

answered 2011-12-05T02:25:06.353
4

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

answered 2011-12-05T06:25:44.323

Your Answer