简体   繁体   English

C ++动态数组写访问冲突

[英]C++ Dynamic Array Write Access Violation

This has been bugging me for almost 2 days now. 这已经困扰了我近两天。 I have in my class definition a 2-D dynamic array: 我在类定义中有一个二维动态数组:

class Raster {

public:
    int pixels[][4];

    void drawTriangle(Vector2f & V1, Vector2f & V2, Vector2f & V3, PixelColor & colorA, PixelColor & colorB, PixelColor & colorC);

};

In my drawing method I have this loop 在我的绘图方法中,我有这个循环

for (int Y = maxY; Y >= minY; Y--) {
    for (int X = minX; X <= maxX; X++) {
        float lambda1;
        float lambda2;
        float lambda3;
        triangle.getBarycentricCoordinate(X, Y, &lambda1, &lambda2, &lambda3);
        if ((0.0f <= lambda1 && 0.0f <= lambda2 && 0.0f <= lambda3)) {
            PixelColor a = lambda1 * colorA;
            PixelColor b = lambda2 * colorB;
            PixelColor c = lambda3 * colorC;
            PixelColor interpolatedColor = a + b + c;
            pixels[Y*width + X][0] = interpolatedColor.R;
            pixels[Y*width + X][1] = interpolatedColor.G;
            pixels[Y*width + X][2] = interpolatedColor.B;

        }
    }
} 

Can anyone point out why it is wrong? 谁能指出为什么这是错误的? Here is the error message: "Exception thrown: write access violation. this was 0x111013530C28FA2." 这是错误消息:“抛出异常:写访问冲突。 是0x111013530C28FA2。”

pixels[][2] doesn't define a non-zero length array here. pixels[][2]此处未定义非零长度的数组。 You need to specify a number for the first dimension too. 您还需要为第一个维度指定一个数字。

I don't think that's a dynamic array. 我不认为这是一个动态数组。

When you declare an array you are required to declare it's size as well. 声明数组时,还需要声明其大小。 You can tell what kind of array it is by what you create it as and what the data is. 您可以通过创建它的形式和数据是什么来判断它是哪种数组。 For instance in the following code : 例如下面的代码:

// Here we can see that the array is a 4X3.
int pixels[][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} };

This would work just fine, because the size of the array is understood. 这样就可以了,因为可以理解数组的大小。

Further i would like to add that if you really want something not restrained by size and want the size to be dynamic depending on the data you have, then you could use the various containers that Standard Template Library offers such as a std::vector. 此外,我想补充一点,如果您确实想要不受大小限制的东西,并且希望大小根据您拥有的数据而动态变化,那么您可以使用标准模板库提供的各种容器,例如std :: vector。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM