Initializing already-created array
Apr 13, 2009 at 12:30pm UTC
I have an array of something, and I know it can be initialized at once:
int a[5] = {1, 2, 3, 4, 5};
but is there a way to easily set all its values at once after it's created? For example:
1 2 3 4
int a[5];
//some other code
a = {1, 2, 3, 4, 5}; //doesn't compile
a[] = {1, 2, 3, 4, 5}; //doesn't compile either
Apr 13, 2009 at 2:28pm UTC
No, not the way you want to do it. You can set all the bytes in the array to a given value using memset(), but other than that, there's no way but for.
Apr 13, 2009 at 6:27pm UTC
Yes, as
helios said, there is no way to do that.
Remember, something like
int a[5] = {1, 2, 3, 4, 5};
is a form of
static initialization , meaning that the array is initialized at compile-time with a constant expression.
If you want to keep the value list and the array declaration separate, you
must introduce a new array, and use one of the <string.h> routines:
1 2 3 4 5 6 7 8 9 10 11 12
#include <string.h>
const int init_a[5] = {1, 2, 3, 4, 5};
int main()
{
int a[5];
memcpy( a, init_a, sizeof ( int ) * 5 );
...
}
Hope this helps.
Topic archived. No new replies allowed.