c++中创建数组时抛出的异常

exception thrown when creating an array c++

本文关键字:异常 创建 数组 c++      更新时间:2023-10-16

我基本上是使用这个算法在游戏中生成一个平面数组,但我无法让它工作,因为当我运行程序时存在一个异常。(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中的每个元素进行一次迭代。但是你每次循环都要增加3次counter。因此,在所有循环的1/3处,counter将到达数组的末端,然后您将开始在数组外写入,这将导致未定义行为。

我不知道你想干什么。为什么每次循环都要写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++;