**The dynamically allocated functions malloc,calloc,realloc in the stdlib library returns the void pointer
I want to convert the void pointer retuned to an array pointer is it possible to do so **
void* x=malloc(6*sizeof(int));
int (*ptr)[3];
Can we typecast x and assign it to ptr ?
CodePudding user response:
You can implicitly convert x
to ptr
via the assignment:
int (*ptr)[3] = x;
or use an explicit cast:
int (*ptr)[3] = (int (*)[3]) x;
As x
is a pointer to array of 6 ints, I am not sure why you want a pointer to the first 3 of these. gcc -Wall -Wextra ...
doesn't even generate a warning for out of bound access printf("%d\n", (*ptr)[4]);
so why use a a plain int *ptr
?
CodePudding user response:
The 'normal' way to do this is
int *ptr = malloc(6*sizeof(int));
or maybe
int *ptr = malloc(3*sizeof(int));
since you dont seem to know if you want 3 or 6 ints