简体   繁体   English

如何在 c 中将 void 指针类型转换为数组指针?

[英]How to type cast an void pointer to array pointer in c?

**The dynamically allocated functions malloc,calloc,realloc in the stdlib library returns the void pointer **stdlib库中的动态分配函数malloc,calloc,realloc返回void指针

I want to convert the void pointer retuned to an array pointer is it possible to do so **我想将返回的 void 指针转换为数组指针,是否可以这样做 **

void* x=malloc(6*sizeof(int));
int (*ptr)[3];

Can we typecast x and assign it to ptr?我们可以类型转换 x 并将其分配给 ptr 吗?

You can implicitly convert x to ptr via the assignment:您可以通过赋值将x隐式转换为ptr

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.由于x是指向 6 个整数数组的指针,我不确定为什么要指向其中前 3 个的指针。 gcc -Wall -Wextra... doesn't even generate a warning for out of bound access printf("%d\n", (*ptr)[4]); gcc -Wall -Wextra...甚至不生成越界访问警告printf("%d\n", (*ptr)[4]); so why use aa plain int *ptr ?那么为什么要使用 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因为你似乎不知道你是想要 3 还是 6 整数

1D array of 6 int : 6 int的一维数组:

int* arr = malloc(6 * sizeof *arr);
...
arr[i] = something;
...
free(arr);

2D array of 2x3 int : 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.在任何一种情况下,都不需要void*作为中间步骤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM