0

I have a struct:

struct foo
{
  void *param;
};

void main(){
  foo object;
}

I need to make object.param point to a dynamically allocated 2D array.

I know this will obviously not work:

//CASE 1
pixel **buf = (pixel**)malloc(16*sizeof(pixel*));
for(int i=0; i<16;i++)
   buf[i] = (pixel*)malloc(16*sizeof(pixel));

object.param = (void **)buf

This works:

//CASE 2
pixel buf[16][16];
object.param = (void *)buf;

My question is:

  1. In case 2 why is buf interpreted as a pointer of type pixel (when in fact buf stores pixel*) which allows it to be cast to a void*?
  2. How do I make case 1 work?
Arkantos
  • 79
  • 1
  • 5

3 Answers3

1

This should work fine:

int main(){
    struct foo object;

    struct pixel **buf = malloc(10*sizeof(struct pixel*));
    for(int i=0; i<10;i++)
    buf[i] = malloc(10*sizeof(struct pixel));

    object.param = buf;
}

The casts weren't necessary, and because this is C you need to use struct pixel instead of pixel.

dbush
  • 205,898
  • 23
  • 218
  • 273
0

The second case works because you can cast any pointer to void*.

For the same reason, the first case will work if you do object.param = (void *)buf, or object.param = buf, as @Iskar comments.

ChronoTrigger
  • 8,459
  • 1
  • 36
  • 57
  • Actually, the casts are unnecessary because any other [object](http://stackoverflow.com/a/10579981/696485) pointer can be converted to a void pointer without an explicit cast. C is not C++. – Iskar Jarak Sep 17 '15 at 01:07
0

Remember, a 2D array in C of type foo[M][N] is really a 1D array of M×N elements and has type foo*. If you declare foo[10][3] a; foo *p = a; then foo[i][j] and p[i*10+j] mean exactly the same thing.

Davislor
  • 14,674
  • 2
  • 34
  • 49