Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set the bounds of an array after object initialisation in cpp

I’m working on an image renderer in cpp that I wrote from scratch (I don’t want to use anything but standard libraries), but I’m having some trouble when trying to store the image. The class I use to store images looks like this:

class RawImage
{
    private:
        RGB pixels[][][3] = {};
    public:
        int width = 0;
        int height = 0;
        RawImage(int width, int height)
        {
            this->width = width;
            this->height = height;
        };
        RGB GetPixel(int x, int y)
        {
            if (x < 0 || x > width - 1)
                return RGB(0.f, 0.f, 0.f);
            if (y < 0 || y > height - 1)
                return RGB(0.f, 0.f, 0.f);
            return pixels[x][y];
        };
        int SetPixel(int x, int y, RGB color)
        {
            if (x < 0 || x > width - 1)
                return -1;
            if (y < 0 || y > height - 1)
                return -1;
            this->pixels[x][y] = color;
            return 0;
        }
};

When I try to compile this code, the g++ compiler gives the following error: declaration of ‘pixels’ as multidimensional array must have bounds for all dimensions except the first.

How do i use a multidimentional array of wich the 2 first dimensions vary in size, but the third dimension is of a fixed size?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Set the bounds of an array after object initialisation in cpp

The size of an array never changes through its lifetime. It’s set upon creation. Technically this isn’t a problem for you because you can initialise the array in the constructor.

But, size of an array variable must be compile time constant, so you cannot accept the size as a constructor parameter.

You can use a dynamic array. Most convenient way is to use std::vector.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading