从单独的函数

时间:2016-01-19 15:49:01

标签: c++ arrays struct

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

MODEL.H:

typedef struct Model{
   Vertex *vertices;
} Model;

Model* newModel();

Model* setVertices(Vertex *vertices, Model *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;
}

DRAWING.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 ++。

非常感谢任何帮助,

感谢。

2 个答案:

答案 0 :(得分:3)

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

这相当于returning a pointer to a local variable,只是有点复杂。

我会推荐C ++方式,并使用std::vector而不是一堆指针。

答案 1 :(得分:1)

您必须添加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与其一起设置。