Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: variable-sized array may not be initialized

I keep having these errors with my array. How am I supposed to return a 2d array of unknown size? I'm trying to manipulate a pbm image by converting it into an array and then doing array manipulations. Here is my code

typedef struct
{
     unsigned char blackWhite;
} PBMPixel;

typedef struct
{
     int x, y;
     PBMPixel *data;
} PBMImage;

This is defined in my header file which hasn't given me any issues. Later on, I have this:

char * ArrayCreate(PBMImage *img, int x, int y)
{
    char ManipArray[x][y];
    int i = 0;
    int j= 0;
    for( i=0; i < x; i++)
    {
        for ( j=0; j < y; j++)
        {
            char ManipArray[i][j] = img->data[(i*(j+1)+j)].blackWhite;
            j++;
        }
        i++;
    }
    return ManipArray;
}

These are the errors I keep getting back:

P-MFunctionHolder.c: In function 'ArrayCreate':
P-MFunctionHolder.c:171:4: error: variable-sized object may not be initialized
P-MFunctionHolder.c:176:2: warning: return from incompatible pointer type [enabled by default]
P-MFunctionHolder.c:176:2: warning: function returns address of local variable [enabled by default]

I'm using MinGW and Windows 8 if that helps, but I doubt that is the problem. I also didn't post the entire code because that's about 260 lines and gives a bunch of the exact same errors.

like image 416
DavidRC Avatar asked Aug 08 '26 18:08

DavidRC


1 Answers

How am I supposed to return a 2d array of unknown size?

A typical solution to this problem is to allocate memory on the heap to a pointer, implicitly passing the responsibility for deallocation to the caller.

For example:

char * ArrayCreate(PBMImage *img, int x, int y)
{
    char *const ManipArray = malloc(x * y * sizeof(char));
    int i = 0;
    int j= 0;
    for( i=0; i < x; i++)
    {
        for ( j=0; j < y; j++)
        {
            ManipArray[i * y + j] = img->data[(i*(j+1)+j)].blackWhite;
            j++;
        }
        i++;
    }
    return ManipArray;
}
like image 81
Brian Cain Avatar answered Aug 10 '26 07:08

Brian Cain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!