5
int (*p)[2];
p=(int(*))malloc(sizeof(int[2])*100);

What is the right way to malloc a pointer to an array? I can't figure out the part with (int(*))

titus
  • 5,512
  • 7
  • 25
  • 39

2 Answers2

9

Posting comments as answer:
In C you should not to cast the return value of malloc. Please refer this post on SO for more information regarding why typecasting return value of malloc is not a good idea in C. And if for some reason you really really want to cast, it should be (int(*)[2]). (int(*)) is int *. The size passed to malloc looks fine (allocating size for 100 pointers to array of 2 ints). So you should be doing

int (*p)[2];
p=malloc(sizeof(int[2])*100); 

Hope this helps!

Community
  • 1
  • 1
another.anon.coward
  • 11,087
  • 1
  • 32
  • 38
-3

It's not clear what you want here. If you want 100 int pairs, for example, arranged as an array of pointers to int (where each pointer points to exactly two ints), then you need to call malloc 100 times on 100 pointers to int, allocating two integers each time.

It just doesn't' make sense to "malloc a pointer to an array". You can malloc an array, and assign that address to a pointer though, or you can malloc an array of pointers. But what you've asked is not clear.

Fooberman
  • 626
  • 5
  • 14
  • 1
    ok, but what if I don't know that I need 100 pointers at runtime? what if I need 10000? I think I'm doing it right – titus Feb 17 '12 at 08:10