Saturday, August 30, 2014

void pointer and pointer arithmetic

Key points

  • its like normal pointer variable but data type is void (eg: void *voidptr) 
  • since its type is void it can able to point any data type( range from int, char,float to user defined data type struct, union)
  • but when dereferencing then it should be casted to respective type
    • *((int *) voidptr)
    • *((float *) voidptr)
    •   ((char*) voidptr)    or     *((char *) voidptr) [see example program]
    • ((struct name *)voidptr)->structurevariable
  • pointer arithmetic will not applicable to void pointer in standard c but in gcc its allowed
  • so using single pointer variable can access multiple data type

int nValue;
float fValue;
struct Something
{
    int nValue;
    float fValue;
};
Something sValue;
void *pVoid;
pVoid = &nValue; // valid
pVoid = &fValue; // valid
pVoid = &sValue; // valid



example 1:

root@selvakumar-Lenovo-B460e:/C_pgms/voidptr# cat void2.c #include<stdio.h> struct Something { char *name; int a; }; int main() { int nValue =10; float fValue =20.2; char *name1 = "god"; char name2[] = "help"; struct Something sValue; sValue.name="selva"; sValue.a=20; void *pVoid; pVoid = &nValue; printf("nValue=%d\n",*((int *)pVoid)); pVoid = &fValue; printf("nValue=%f\n",*((float *)pVoid)); pVoid = name1; 
// note than not giving the address since its already pointer *name1 printf("name1=%s\n",((char *)(pVoid))); pVoid = name2; 
// note than not giving the address since its already array name2[]
printf("name2=%s\n",((char *)(pVoid)));
pVoid = (sValue.name); // valid printf("name=%s\n",((char *)(pVoid))); pVoid = &(sValue); printf("struct something sValue->a =%d\n",((struct Something *)(pVoid))->a); return 0; } root@selvakumar-Lenovo-B460e:/C_pgms/voidptr# gcc void2.c root@selvakumar-Lenovo-B460e:/C_pgms/voidptr# ./a.out nValue=10 nValue=20.200001 name1=god name2=help name=selva struct something sValue->a =20 root@selvakumar-Lenovo-B460e:/C_pgms/voidptr#


root@selvakumar-Lenovo-B460e:/C_pgms/voidptr# cat voidptr.c #include<stdio.h> enum Type { INT, FLOAT, STRING, }; void Print(void *pValue, enum Type eType) { int i;float f;char *c; switch (eType) { case INT: i = *((int *)pValue); printf("\n%d\n",i); break; case FLOAT: f = *((float *)pValue); printf("\n%f\n",f); break; case STRING: c = (char *)pValue; printf("\n%s\n",c); break; } } int main() { int nValue = 5; float fValue = 7.5; char *szValue = "Mollie"; Print(&nValue, INT); Print(&fValue, FLOAT); Print(szValue, STRING); // note here no & symbol useed for char pointer return 0; } root@selvakumar-Lenovo-B460e:/C_pgms/voidptr# gcc voidptr.c root@selvakumar-Lenovo-B460e:/C_pgms/voidptr# ./a.out 5 7.500000 Mollie root@selvakumar-Lenovo-B460e:/C_pgms/voidptr#



No comments:

Post a Comment