**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?
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 aa plain int *ptr
?
int *ptr = malloc(6 * sizeof(int));
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
1D array of 6 int
:
int* arr = malloc(6 * sizeof *arr);
...
arr[i] = something;
...
free(arr);
2D array of 2x3 int
:
int (*arr)[3] = malloc( sizeof(int[2][3]) );
...
arr[i][j] = something;
...
free(arr);
In either case there is no need of a void*
as a middle step.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.