0

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;)?

4

3 回答 3

3

这可以通过存储 a 来简化std::vector<float>

#include <vector>

struct arr_ {
   std::vector<float> a;
};

在 C++11 中,初始化很简单:

arr_ x{ {1.0f, 2.0f, 3.0f, 4.0f, 5.0f} };

不幸的是,在 C++03 中没有简单的方法来执行这样的初始化。一种选择是从临时固定大小的数组初始化:

float farray_[5] = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f};
arr_ x{ std::vector<float>(farray_, farray_+5)};
于 2013-06-26T07:33:33.237 回答
1

您可以初始化一个然后复制/到您array的动态内存。但是按照建议使用将是更好的选择。stackmemcpyvector

于 2013-06-26T07:34:32.313 回答
0

xa 是一个指针,当您更改 xa = xx 时,您会更改地址

试试这个代码:

xa =浮点数(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) ;

于 2013-06-26T07:35:29.127 回答