c++ - 在C++中将指针设置为指针数据

标签 c++ pointers

我一直在创建一个函数,该函数应该返回一个包含指向指针的指针的结构。问题是我无法访问数据:/

问题是这样的:

struct openGLmodel
{

    struct subM
    {

        Vec3*      positions;
        Vec3*      normals;

        int        nbrVertices;

        int        nbrTriangles;
        int*       triangleIndices;
    };

    dim_type  subModelCount;
    subM*     subModel;
}

函数通过以下方式构建模型:

openGLmodel createModel(..model data)
{

openGLmodel model;

std::vector<openGLmodel::subM>* subModels = new std::vector<openGLmodel::subM>; 

std::vector<Vec3>* positions = new std::vector<Vec3>;
std::vector<Vec3>* normals = new std::vector<Vec3>;

int subModelIndex = 0;

for(...all vertices...)
{
    ... //extracting positions and normal vectors

    positions->push_back(pos);
    normals->push_back(normal);

    if(positions->size() >= 65536)
    {
        subModels->push_back(openGLmodel::subM());

        subModels->at(subModelIndex).positions = positions->data();
        subModels->at(subModelIndex).normals = normals->data();


        std::vector<Vec3>* positions = new std::vector<Vec3>;
        std::vector<Vec3>* normals = new std::vector<Vec3>;

        subModelIndex++;
    }
}

...
... 


model.subModel = new openGLmodel::subM[subModelIndex]();

for(int i=0; i<subModelIndex; i++)
{
    model.subModel[i] = openGLmodel::subM();

    model.subModel[i].positions = subModels->data()[i].positions;
    model.subModel[i].normals = subModels->data()[i].normals;

}

return model;

}

subModels 包含正确的数据但 model.subModel 不是。我怎样才能让模型访问 vector 中的数据?最后一个for循环似乎是错误的..

最佳答案

您访问的原因:

 model.subModel[i]

当那只是类型时:

subM*     subModel;

您正在访问不应访问的内存。

附带说明一下,您的代码过于复杂且危险。 您可以删除实际上不需要的大部分指针。

std::vector<openGLmodel::subM>* subModels = new std::vector<openGLmodel::subM>; 

std::vector<Vec3>* positions = new std::vector<Vec3>;
std::vector<Vec3>* normals = new std::vector<Vec3>;

成为

std::vector<openGLmodel::subM> subModels;    
std::vector<Vec3> positions;
std::vector<Vec3> normals;

和你的结构

struct openGLmodel
{

    struct subM
    {

        Vec3 positions;
        Vec3 normals;
        int  nbrVertices;

        int        nbrTriangles;
        std::vector<int> triangleIndices;
    };

    dim_type  subModelCount;
    subM*     subModel;
}

如果您需要重用现有 vector 而不是到处复制它们,您可以只使用对 vector 的引用并在构造函数的初始化列表中对其进行初始化。

关于c++ - 在C++中将指针设置为指针数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31477550/

相关文章:

c++ - 如何在 C++(g++ 编译器)中初始化 unordered_set?

c++ - 防止 GDB 中的 PLT(过程链接表)断点

c - 在 C 中,我如何选择是返回结构还是指向结构的指针?

结构数组的 C++ 选择排序

c++ - DLL 中的全局指针

c++ - 使用 CMake 编译具有多配置的 Boost

c++ - 当没有传递任何参数时,#__VA_ARGS__ 应该生成什么?

c++ - 继承,使基成员变量为const

c++ - 与派生类的虚指针混淆

c++ - C/C++ 中的 (nil) 指针