【发布时间】:2018-06-13 17:24:44
【问题描述】:
我在 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: %f\n",
*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
感谢您的想法和耐心;)
【问题讨论】:
-
这段代码中有很多内容。你为什么
new一切?为什么使用大小为 1 的数组?为什么在 C++ 中使用printf?你为什么typedef你的struct?看来您可能正在混合使用 c 和 c++ 教程。学习 c++ 时避免使用 c 教程。 -
停止使用这么多指针和
new现在。使用std::vector。 C++ 不是 C。 -
This 和你写的差不多,格式化后更容易看到
data是如何初始化的。每个Data有三个news。
标签: c++ arrays pointers data-structures struct