Solved

# Assigning an array using {}'s

Posted on 2007-04-07
179 Views
I have an array of floats that is declared like:

float x1[3];

I then later want to do something like:

x1 = {1.5,3.2,4.5};

but it seems I can only do that on initialisation. Is there some way to do this such as using an array copy routine?
0
Question by:MrModest
• 2

LVL 53

Accepted Solution

Infinity08 earned 250 total points
ID: 18869523
>> but it seems I can only do that on initialisation.

Indeed. The { } syntax for array initialization can only be used when defining/declaring the array :

float x1[3] = {1.5,3.2,4.5};

You could do something like this if you really need it :

float x1[3] = { 0.0 };  // <---- initialize to all 0's

{
float x1_tmp[3] = {1.5,3.2,4.5};                // <---- create a temporary array with the values we want ...
memcpy(x1, x1_tmp, 3 * sizeof(float));      // <---- copy that temporary array into the x1 array
}

for (int i = 0; i < 3; ++i) {     // <---- the x1 array now contains the desired values
cout << x1[i] << endl;
}

Of course you could also use a function to populate your array :

void populate_array(float (&x1)[3]) {
float x1_tmp[3] = {1.5,3.2,4.5};                // <---- create a temporary array with the values we want ...
memcpy(x1, x1_tmp, 3 * sizeof(float));      // <---- copy that temporary array into the x1 array
return;
}

and call it like this :

float x1[3] = { 0.0 };  // <---- initialize to all 0's

populate_array(x1);

for (int i = 0; i < 3; ++i) {     // <---- the x1 array now contains the desired values
cout << x1[i] << endl;
}
0

LVL 53

Expert Comment

ID: 18869528
Oh, and a good idea is to inline that function :

inline void populate_array(float (&x1)[3]) {
float x1_tmp[3] = {1.5,3.2,4.5};                // <---- create a temporary array with the values we want ...
memcpy(x1, x1_tmp, 3 * sizeof(float));      // <---- copy that temporary array into the x1 array
return;
}
0

Author Comment

ID: 18869538
Thanks, I figured I would have to do something like that.
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
The viewer will learn how to use and create new code templates in NetBeans IDE 8.0 for Windows.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.