0

**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 ?

3
  • void pointers can be cast to any other pointer type. So ptr = x; should be fine. Commented Apr 19, 2022 at 3:13
  • ... That is, void pointers can be converted implicitly, by assignment, to any other object pointer type. They may also be converted explicitly via a cast. So "yes" and "yes". The allocation functions wouldn't be much use if you couldn't use them to get pointers of the required types. Commented Apr 19, 2022 at 3:21
  • 1
    Why do you want to do this? x points to an array of 6 ints, and ptr is a pointer to an array of 3 ints. Commented Apr 19, 2022 at 3:29

3 Answers 3

1

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?

int *ptr = malloc(6 * sizeof(int));
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

The OP might want to allocate a 2D array 2x3, in which case int (*ptr)[3] = malloc(2*3*sizeof(int)); is perfectly fine and correct, unlike int* which would be wrong in that case.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.