持有不同值类型的空指针的C数组

我正在尝试使用3个指针的void数组:

char v1='c'; 
int v2 =12;
int const numOfArgs=3;
char v3[3] = "geo";
void *arg1 = &v1;
void *arg2 = &v2;
void *arg3 = &v3;
void *ptrs[numOfArgs]= {arg1,arg2,arg3};

I tried in several ways to use one of the pointers from ptrs, including casting ,but nothing worked.

我应该如何处理?

评论
Cara
Cara

首先

char v3[3] = "geo";

does not have enough space to append '\0' (C-strings are null-terminated).

因此将其更改为

char v3[4] = "geo";

In order to get the values from void *ptrs[numOfArgs], type-casting will work. And don't forget to dereference when needed.

这是一个例子:

printf("\n%c", *(char*)ptrs[0]);
printf("\n%d", *(int*)ptrs[1]);
printf("\n%s", (char**)ptrs[2]);

输出:

c
12
geo
点赞
评论