DavidRC
DavidRC

Reputation: 103

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.

Upvotes: 3

Views: 481

Answers (1)

Brian Cain
Brian Cain

Reputation: 14619

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;
}

Upvotes: 2

Related Questions