Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

malloc pointer to array

Tags:

c

malloc

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(*))

like image 284
titus Avatar asked Feb 17 '12 08:02

titus


1 Answers

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!

like image 61
another.anon.coward Avatar answered Sep 20 '22 03:09

another.anon.coward