[英]exception thrown when creating an array c++
我基本上使用这个算法在我的游戏中为平面生成一个数组,但是我无法让它工作,因为我运行程序时出现异常。 (GLuint 只是 opengl 中的 unsigned int)
const GLuint planeDimension = 30.0f;
const GLuint half = planeDimension / 2;
const GLuint verticesCount = planeDimension * planeDimension;
int counter = 0;
GLfloat planeVertices[verticesCount];
for (GLuint length = 0; length < planeDimension; length++) {
for (GLuint width = 0; width < planeDimension; width++) {
planeVertices[counter++] = length - half;
planeVertices[counter++] = 0.0f;
planeVertices[counter++] = width - half;
}
}
您正在循环中访问数组外部。 您的循环对planeVertices
每个元素都进行了一次迭代。 但是每次循环都会将counter
递增 3 次。 因此,通过所有循环counter
大约 1/3 将到达数组的末尾,然后您将开始在数组外写入,这会导致未定义的行为。
我不确定你想做什么。 为什么每次循环都要写数组的 3 个不同元素? 所以目前还不清楚如何修复它。 您可以简单地将其声明为 3 倍:
GLfloat planeVertices[verticesCount * 3];
或者您可以将其声明为二维数组:
GLfloat planeVertices[verticesCount][3];
然后你的循环会做:
planeVertices[counter][0] = length - half;
planeVertices[counter][1] = 0.0f;
planeVertices[counter][2] = width - half;
counter++;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.