我有一个指针结构的数组,像这样:错误,动态分配对象到一个数组
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?
'memcpy'中的'sizeof(Vector)* index'是错误的。您没有分配那么多'Vector's,所以您不能将那么多的内存复制到该位置 – 2012-07-16 00:43:47
调试器知道。你有没有试过使用它? – 2012-07-16 00:44:37
你的代码片段中有许多可疑的东西,但最终没有足够的信息让我们做任何事情,除了猜测。您需要使用调试器来识别问题,或者至少帮助您构建一个[最小测试用例](http://sscce.org)。 – 2012-07-16 00:45:20