简体   繁体   中英

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."

pixels[][2] doesn't define a non-zero length array here. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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