Reputation: 41
I have a struct with pointers to floats that i want to turn into an array of an indeterminate size. At the beginning of my program I want to declare a few of these structs and turn them into different sized arrays, like this:
struct _arr {
float * a;
}
...
_arr x;
x.a = (float *)malloc(sizeof(float)*31);
x.a = { 6,
1, 1, 1, 0 , 0 ,
1, 0, 1, 0 , 0.0625,
1, 1, 0, 0.0625, 0 ,
1, 0, 1, 0 , 0.0625,
1, 0, 0, 0.0625, 0.0625,
1, 1, 0, 0.0625, 0
};
Unfortunately this doesn't work, does anyone have any suggestions get the values into the array besides adding in each value in individually (such as a[0] = 6;)?
Upvotes: 0
Views: 1100
Reputation: 227390
This could be simplified by storing a std::vector<float>
:
#include <vector>
struct arr_ {
std::vector<float> a;
};
In C++11, the initialization is trivial:
arr_ x{ {1.0f, 2.0f, 3.0f, 4.0f, 5.0f} };
Unfortunately, there is no trivial way to perform such an initialization in C++03. One option would be to initialize from a temporary fixed size array:
float farray_[5] = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f};
arr_ x{ std::vector<float>(farray_, farray_+5)};
Upvotes: 3
Reputation: 436
x.a is a pointer and when you change x.a = xx you change the address
try this code:
x.a = new float( 6, 1, 1, 1, 0 , 0 , 1, 0, 1, 0 , 0.0625, 1, 1, 0, 0.0625, 0 , 1, 0, 1, 0 , 0.0625, 1, 0, 0, 0.0625, 0.0625, 1, 1, 0, 0.0625, 0 ) ;
Upvotes: 0
Reputation: 31952
You can initialize an array
on the stack
and then copy/memcpy
to your dynamic memory. But using vector
as suggested would be the better choice.
Upvotes: 1