3

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.

2
  • can you try char ** arraycreate(PBMImage,int x,int y) Commented Jul 21, 2013 at 5:24
  • char ManipArray[i][j] = img->data[(i*(j+1)+j)].blackWhite; --> maybe ManipArray[i][j] = img->data[(i*(j+1)+j)].blackWhite;. also j++; and i++; twice. BAD! return ManipArray; out of the scope. Commented Jul 21, 2013 at 10:45

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this worked, however it's giving me another error I was about to post another question for: P-MFunctionHolder.c: In function 'ArrayCreate': P-MFunctionHolder.c:190:26: error: subscripted value is neither array nor pointer nor vector

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.