如何填充包含指针数组的结构数组

How to fill array of struct containing pointer arrays

本文关键字:数组 指针 结构 包含 何填充 填充      更新时间:2023-10-16

我在C++有一个非常简单的小问题。我想填充包含双数组的结构数组。我该怎么做?

typedef struct 
{
double *inputs[2];
double *target[1];
} Data;
Data data[] 
{
new double[2]{10, 20}, new double[1]{30},
new double[2]{40, 50}, new double[1]{60},
new double[2]{70, 80}, new double[1]{90},
new double[2]{100, 110}, new double[1]{120} 
};

main()

printf("data[0]: inputs: %f %f, targets: %fn",
*data[0].inputs[0],
*data[0].inputs[1],
*data[0].target[0]);

这是我的想法,但是当我运行时,它会打印这个:

data[0]: inputs: 10.000000 30.000000, targets: 40.000000

当然,在数组数据的末尾(如第 3 项或第 4 项(,它会导致UNAUTHORIZED ACCESS TO MEMORY

感谢您的想法和耐心;)

使用现代 c++ 使您的代码更简单、更安全:

#include <iostream>
#include <array>
#include <vector>
struct Data {
std::array<double,2> inputs;
std::array<double,1> target;
};
int main()
{
std::vector<Data> data = {
{ {10, 20}, {30} },
{ {40, 50}, {60} },
{ {70, 80}, {90} },
{ {100, 110}, {120} }
};
std::cout << "data[0]: inputs: " << data[0].inputs[0] << " " << data[0].inputs[1] << ", targets: " << data[0].target[0] << "n";
}

您最初的问题是double *inputs[2]声明了一个指向double的 2 元素指针数组,而不是指向 2 元素数组的指针doubles

您的Data结构包含 2 个字段、2 个double指针数组和 1 个double指针数组。

这意味着初始最多需要 3 个double指针,这意味着在您的初始中确实看起来像这样

Data data[]{
{new double[2]{ 10, 20 },   new double[1]{ 30 },        new double[2]{ 40, 50 }}, //1st object
{new double[1]{ 60 },       new double[2]{ 70, 80 },    new double[1]{ 90 }}, //2nd object
{new double[2]{ 100, 110 }, new double[1]{ 120 }} //3rd object but 2 parameters??
};

尝试在循环中打印它时,第三个对象将导致段错误,因为target字段尚未正确启动(使用 Visual Studio 调试时,它设置为 null,不确定其他编译器(。

你的问题在这里:

typedef struct {
double *inputs[2];  // this
double *target[1];  // this
} Data;

这是一个指针数组,希望假设它表现为动态 1D 数组。 简单的解决方法是:

struct Data {
double *inputs = nullptr;
double *target = nullptr;
} ;

但是,您使用new进行大量堆内存分配,这使得delete繁琐的任务变得非常困难,因此数据结构的管理非常困难。 我强烈建议您使用std::vector<>,这使您的任务更轻松、更干净。

#include <vector>
#include <iostream>
struct Data
{
std::vector<double> inputs; // use  instead of double *inputs[2];
std::vector<double> target; // use  instead of double *target[1];
//Data(const std::vector<double>& a, const std::vector<double>& b) :inputs(a), target(b){}
};
int main()
{
std::vector<Data> data = // now in your main structure array
{  { {10, 20}, {30} },
{ {40, 50}, {60} },
{ {70, 80}, {90} },
{ {100, 110},{120} }
};
// access using range based loop now
for(const Data& each_strcut: data)
std::cout << each_strcut.inputs[0] << " " << each_strcut.inputs[1]
<<"t" << each_strcut.target[0] << std::endl;
return 0;
}