1

How do I allocate memory to integer type (*a)[2] ? I am comfortable doing it with **a, *a etc. etc., also *a[2], but this looks different.

Can somebody help out ? Thanks in advance.

Lalit
  • 29
  • 6
  • 1
    What is the type of `a`? How did you find yourself in this pickle? – Floris May 10 '13 at 02:49
  • Welcome to SO. :) here on SO, you can *accept* an answer given to you, if it helped you. You get +2 rep points too. (we accept by clicking on the big empty V sign next to the answer). :) – Will Ness May 11 '13 at 07:54

1 Answers1

3

Same as for any pointer type, say you have

int (*a)[2];

a pointer a to arrays of 2 int, then you allocate

a = malloc(number_of_rows * sizeof *a);

to get a block of number_of_rows * (2 * sizeof (int)) bytes.

You then access that with

a[i][j]

with 0 <= i < number_of_rows and 0 <= j < 2.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
  • Very true, thank you. But how does casting really take place here ? - i think i can compare this with a struct now ? – Lalit May 10 '13 at 03:01
  • What casting? The `void*` returned by `malloc` is implicitly converted to `int(*)[2]` for the assignment. The memory layout is as if you had an `int array[number_of_rows][2];` and then `a = &array;`. You can indeed compare it with `struct foo *bar; bar = malloc(number_of_rows * sizeof (struct foo));`, the `int[2]` is analogous to `struct foo` then. – Daniel Fischer May 10 '13 at 03:07
  • Good answer; this is a trick I didn't know for making a 2D array, and it risks making my brain explode to think about it. In my experience some compilers will complain that the `void *` return type of `malloc` cannot be implicitly converted to another type, and require casting. How would you do that? `a = (int(*)[2])malloc()`? – Floris May 10 '13 at 03:13
  • I think its not getting converted. Also, the casting needs to be conveyed, (that is how can it be implicit), malloc needs to be told that somehow ... ? – Lalit May 10 '13 at 03:16
  • Ah, those would be C++ compilers. Generally I would advise avoiding to compile C with C++ compilers if possible. But if you have to, then yes, you have gotten the cast exactly right. – Daniel Fischer May 10 '13 at 03:16
  • Thank you, that works. Increased my knowledge of debugging hard pointers a bit. Thanks a lot guys. – Lalit May 10 '13 at 03:18