从单独函数中的结构中检索数组成员

Retrieve array member from struct in separate function

本文关键字:检索 数组 组成员 结构 单独 函数      更新时间:2023-10-16

我在从结构中检索某些值时遇到问题。在下面的简化片段中,struct Model 的顶点成员包含一个值数组,如果在其中调用 drawModel() 调用 buildModel(),则可以正确检索这些值。但是,如果我调用 buildModel() 然后调用 drawModel(),则没有错误,但不会使用正确的值检索顶点。这让我相信要么变量作用域结束,要么我错误地传递引用,要么需要使用 malloc 在堆上定义顶点成员。

型。H:

typedef struct Model{
   Vertex *vertices;
} Model;
Model* newModel();
Model* setVertices(Vertex *vertices, Model *model);

型。.CPP:

Model* newModel(){
   Model* model;
   model = (Model* )malloc(sizeof(Model));
   //model->vertices = (Vertex *)malloc(sizeof(Vertex)); This did not help...
   return model;
}
Model* setVertices(Vertex *vertices, Model *model){
   model->vertices = vertices;
   return model;
}

绘图。.CPP:

Model* buildModel(){
   Model* model = newModel();
   Vertex vertices[] = {
      { XMFLOAT3(-1.0f, 5.0f, -1.0f), (XMFLOAT4)colorX},
      ...  //Abbreviated declaration
   };
   model = setVertices(vertices, model);
   //drawModel(model);    Calling drawModel() here retrieves vertices correctly
   return model;
}
void drawModel(Model *model){
   loadVertices(d3dDeviceRef, 11, model->vertices); //Trying to pass vertices array here
}

这在学习中非常有用,并且我尝试尽可能少地使用课程,并在可能的情况下走更多的 C 路线而不是C++。

任何帮助将不胜感激,

谢谢。

vertices数组是 buildModel 函数的本地数组。一旦函数返回,数组就消失了。

这相当于返回指向局部变量的指针,只是稍微复杂一些。

我建议使用C++的方式,并使用std::vector而不是一堆指针。

您必须在struct Model中添加一个int来存储顶点的数量,并在程序的其余部分考虑它:

typedef struct Model{
   Vertex *vertices;
   int nVertices; // add this
} Model;

然后你必须像这样newModel()分配内存:

model = (Model* )malloc(nVertices*sizeof(Vertex)+sizeof(int)); // this will allocate the necessary space 

(此时,必须定义顶点数)

然后使用 memset() 将分配的内存设置为零(如果需要)
然后添加到setVertices();一个新的int参数以发送顶点数并设置model->nVertices