views:

220

answers:

6
+3  Q: 

About c arrays...

I know that you can declare an array in C like this:

int nums[5] = {0,1,2,3,4};

However, can you do this?

int nums[5];
// more code....
nums = { 0,2,5,1,2};

In other words, can I initialize the array using the bracket notation at any other time than just the declaration? Thanks for your time, Sam

+1  A: 

That's just not possible

victor hugo
+1  A: 

Simple answer: no.

Initializing a C array is only possible at the time of its declaration.

Zifre
+3  A: 

The standard states that it is not possible to assign to all elements of an array at once using an assignment expression. You can only do that during declaration.

But you can achieve what you're trying to do by copying using standard functions.

Suvesh Pratapa
You guys are awesome! You answer so quickly! You totally make me feel better. It was driving me crazy.Thanks. ;)
+1  A: 

Nope. The declaration in your example...

int nums[5] = {0,1,2,3,4};

...is called an initializer. Initializers are part of the data declaration which specifies the initial values of your array elements.

If you create the array without the initializer, you are out of luck. You have to assign values to the array elements the old-fashioned way.

Enjoy,

Robert C. Cartaino

Robert Cartaino
+17  A: 

It's not possible in C89 (what most C compilers target). C99 is supported by a few, and has compound literals:

int nums[5];
memcpy(nums, (int[5]){1, 2, 3, 4, 5}, 5 * sizeof(int));

You however cannot assign to an array. You can only copy to its memory. You would need another array that you copy from in C89

int nums[5]; 
int vals[] = { 1, 2, 3, 4, 5 };
memcpy(nums, vals, sizeof vals);

Note that the sizeof operator returns the size of its operand in bytes.

Johannes Schaub - litb
Wow, cool, I didn't know that. :) I don't think I've ever actually seen that in real code. All reasonable compilers these days support C99, so that might be useful.
Zifre
That's really cool
ZelluX
A: 

you can declare nums as pointer.

int * nums;

then you can assign an array to that pointer at a later time:

int tmp[5] = {0,1,2,3,4};

nums = tmp;
codymanix