首页 > 解决方案 > 从自定义结构数组中提取数据

问题描述

我正在尝试制作一组​​粒子并为每个粒子分配一个从随机正态分布中挑选的 x、y 和 z 坐标。我想看看我得到了什么位置,并决定显示我的 x 坐标。这基本上就是我正在做的事情:

#include <omp.h>
#include <time.h>
#include <iostream>
#include <cmath>
#include <random>

using namespace std; 
struct PARTICLE { 
public:   
double x;   
double y; 
double z;
PARTICLE() {   } };

int main() {

//set up cluster of particles   
int numberOfParticles = 10;   
std::random_device rd{};   
std::mt19937 gen{rd()};   
std::normal_distribution<> d{0,1};

PARTICLE *clusterOfParticles [numberOfParticles];

for (int ind=0; ind<numberOfParticles; ind++){
    cout<<"test"<<endl;
    clusterOfParticles[ind]->x = d(gen);
    cout<<clusterOfParticles[ind]->x<<endl; }

return 0; 
}

我没有收到任何错误消息,并且可以看到正在显示“测试”。但我没有看到我的 x 坐标。它们甚至被存储在内存中吗?我哪里错了?

标签: c++struct

解决方案


您问题下方的评论基本上已经给出了答案。您的指针数组指向任何地方。

而且您使用的是 C99 样式可变长度数组 (VLA)。这在 C++ 中是不允许的。

我不想,但无论如何我都会用指针向你展示解决方案。采用:

PARTICLE *clusterOfParticles = new PARTICLE [numberOfParticles];

// Your code

delete [] clusterOfParticles;

但我不想那样做。相反,我说:

以后永远不要使用 C 样式数组。没有必要。

不要使用指针。永远不要使用原始指针。忘记上面的例子。至少使用 std::unique_ptr。

将您的代码修改为

// We will use a vector
std::vector<PARTICLE> clusterOfParticles(numberOfParticles);

for (int ind=0; ind<numberOfParticles; ind++){
    cout<<"test"<<endl;
    clusterOfParticles[ind].x = d(gen);
    cout<<clusterOfParticles[ind].x<<endl; }

更简单,更不容易出错。


推荐阅读