Hi All,
I am trying to write a common function called call which will take in a void* and an int type. Based on the int type it will have access to different structures. The code doesn't compile in the first place. I am not sure this is correct or not, cause I am accessing something from a void*. Can you please help me with some suggestions?

typedef struct a{

    int x;
    char y;
}as, *ap;

typedef struct b{

    int m;
    char n;
}bs, *bp;

void call(void *ptr, int i)
{
    if(i == 1){

        printf("\n x : %d", ptr->x);
        printf("\n y : %c", ptr->y);
    }
    if(i == 2){
        printf("\n x : %d", ptr->m);
        printf("\n y : %c", ptr->n);
    }
    return;
}

int main(int argc, char *argv[])
{

    as aobj;
    aobj.x = 1;
    aobj.y = 'A';

    bs bobj;
    bobj.m = 2;
    bobj.n = 'B';

    call(&(aobj),1);
    call(&(bobj),2);

    return 0;
}

Follwing is the error I get

error #2131: expression must have pointer-to-class type
printf("\n x : %d", ptr->x);
error #2131: expression must have pointer-to-class type
printf("\n y : %c", ptr->y);
error #2131: expression must have pointer-to-class type
printf("\n x : %d", ptr->m);
error #2131: expression must have pointer-to-class type
printf("\n y : %c", ptr->n);

Thanks in advance.

@ahamed101:

In my knowledge your usage of void * pointers are wrong.

The sole purpose of introduction of void * pointers in C is to include the concept of polymorphism and the basic limitation of void * pointers says that it cannot be dereferenced.

that is:

int *p,x=10;
void *v;

p=&x;    // Correct
printf("%d",*p);  //Correct
v=p;   //Correct

printf("%d",*v);  // Error as void* pointers cannot be dereferenced

Mostly they are used as intermediate elements in type casting of pointers.BUT CANNOT BE USED TO REFER TO VARIABLES DIRECTLY.

You are right... "void * pointers says that it cannot be dereferenced"... I almost forgot that...
thanks...

This question has already been answered. Start a new discussion instead.