如何填充包含指针数组的结构数组
How to fill array of struct containing pointer arrays
我在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;
}
相关文章:
- 添加到数组指针
- C++语法差异:二维和一维数组(指针算术)
- 数组指针表示法C++(移动数组时)
- 复制后删除原始数组指针将前 3 个字节设置为 0
- C++访问指向结构的指针中的类数组指针
- C++编译时使用 constexpr 字符数组指针分配静态数组?
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- 创建<int>对整数数组指针的矢量引用 (C++)
- 将 2D 数组指针传递给 C++ 中的函数
- 创建指针是否超过非数组指针的末尾,而不是从 C++17 中的一元运算符和未定义的行为派生?
- 队列数组指针 (C++)
- C++数组指针上的删除操作
- 对于循环不循环和检测字符数组 [指针和字符数组]
- 如何初始化数组指针对象
- 如何正确传递 2D 数组指针作为参数
- 从数组指针中获取怪异的数字
- 初始化std :: unique_ptr作为原始数组指针的初始化
- 将结构数组指针从C#传递到C
- STD :: Sort将数组指针设置为NULL
- C++数组指针错误无法将“int*”转换为“int**”