C array of void pointers holding different value types

Viewed 227

I'm trying to have a void array with 3 pointers:

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.

How should I approach to it?

3 Answers

Firstly

char v3[3] = "geo";

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

So change it to

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.

Here is an example:

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

Output:

c
12
geo
void *ptrs[numOfArgs]= {arg1,arg2,arg3};

When you compile your code, you can get the error:

variable-sized object may not be initialized

If you want to declare the array on this way, you have to make the constant variable numOfArgs by #define:

#define numOfArgs 3

Or you can initialize each element of array of pointer as:

    void *ptrs[numOfArgs];
    ptrs[0] = &v1;
    ptrs[1] = &v2;
    ptrs[2] = &v3;

The problem with this line:

void *ptrs[numOfArgs]= {arg1,arg2,arg3};

Is that ptrs is a variable length array. Such arrays are not allowed to be initialized because the size it determined at run time. It doesn't matter that numOfArgs is declared as const.

You can only initialize an array if its size is a compile time constant, or more formally a constant expression. You can satisify this requirement if the size is a macro.

#define numOfArgs 3
Related