我有一个指向结构数组的指针,如下所示:
class Terrian {
...
private:
Vector *terrian_vertices;
...
}
并且指针的数据在“construct_vertices”函数中生成
Terrian::Terrian(int width, int height) {
this->width = width;
this->height = height;
std::cout << "Width: " << width << " Height: " << height << "\n";
std::cout << "Vertices\n";
construct_vertices();
std::cout << "Element\n";
construct_elements();
std::cout << "Buffers\n";
construct_buffers();
}
void Terrian::construct_vertices() {
terrian_vertices = new Vector[width * height];
std::cout << "Generating data\n";
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int index = x + y * width;
Vector *pos = new Vector((GLfloat)x, 0.0f, (GLfloat)-y);
memcpy(pos, terrian_vertices, sizeof(Vector) * index);
std::cout << terrian_vertices[index].x;
Color *color = new Color(0, 255, 0);
memcpy(color, terrian_colors, sizeof(Color) * index);
}
}
}
这是程序的输出(我在主函数中所做的只是实例化对象)
Width: 32 Height: 32
Vertices
Generating data
5.2349e-039
Process returned -1073741819 (0xC0000005) execution time : 10.073 s
Press any key to continue.
当第一个指针被复制到数组时程序崩溃,'x' 的输出应该是 0。这令人费解。有谁知道是什么导致这种情况发生?如果是这样,是否有更好的方法来动态分配结构 - 不使用 memcpy?