从单独函数中的结构中检索数组成员
Retrieve array member from struct in separate function
我在从结构中检索某些值时遇到问题。在下面的简化片段中,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
。
相关文章:
- 初始化类中的指针数组,并在另一个类中检索它
- 从C++(非托管代码)检索数组到 C 尖锐形式(托管)
- 我正在编写一个代码来将 int 数组存储在文件中,然后用 c++ 检索它,但是检索第一项是假值,我该如何解决这个问题?
- Getter 函数,用于在 2d 数组是类的数据成员时检索 2d 数组元素
- ifstream不使用C 中的数组检索数据
- 无法从数组二次表达式中检索数据值
- 如何从DLL检索数组变量?(视觉C )
- 当我将字符串数组从 VBA 传递到 c++ 并将它们用作映射中的键时,为什么我无法从映射中检索数据(使用键)
- 如何在三维数组中使用std::map来存储/检索具有特定值的键
- 检索字符数组数据时出现问题
- 如何在 C++ 中传递和检索 char 数组
- 以数组的形式存储组合框项,并在 WPF 中检索 SelectedId
- 正在从数组中检索变量
- 如何检索智能指针数组的大小?(例如std::unique_ptr<int[]>)
- 无法从数组中检索字符串
- 如何使用 c++ 将值检索到数组中
- 从单独函数中的结构中检索数组成员
- 如何将数组添加到CvSeq,以及如何检索数组
- 检索数组的最干净的方法是什么?
- 通过 CComPtr 调用检索数组<IDispatch>