Difference between void pointer and generic pointer?

Showing Answers 1 - 1 of 1 Answers

baseersd

  • Oct 31st, 2007
 

When a variable is declared as being a pointer to type void it is known as a generic pointer. Since you cannot have a variable of type void, the pointer will not point to any data and therefore cannot be dereferenced. It is still a pointer though, to use it you just have to cast it to another kind of pointer first. Hence the term Generic pointer.

This is very useful when you want a pointer to point to data of different types at different times.

Here is some code using a void pointer:

#include <stdio.h>
int main()
{
    int  num[3] = {10,20,30};
    char name[30] = "Welcome to C World";
    int *pint = NULL;
    void *pvoid = NULL;
    int i;
   
   
    pint = &num;
    for ( i=0; i<3; i++ )
     printf("%d ",*(pint + i ));
     printf("n");
    
     // The same can be done using void pointer as follows.
     pvoid = &num;
    for ( i=0; i<3; i++ )
     printf("%d ",*((int *)pvoid + i ));
    
     // Same void pointer can be cast to char.
     printf("n");
     pvoid = name;
     for( i=0; i < strlen( name); i++ )
          printf("%c", *((char *) pvoid + i));
    getch();
}

  Was this answer useful?  Yes

I just want to make a small point.
When you assign an array to a pointer, you can't put an & sign

int arr[5]={1,2,3},*p1;
p1=arr;

This will work


int arr[5]={1,2,3},*p1;
p1=&arr;

 error: cannot convert `int (*)[5]' to `int*' in assignment

This is a small mistake in the code segment given in the above example

  Was this answer useful?  Yes

bhargav

  • Apr 23rd, 2016
 

Actually I am asking you question that is, Why should not we use & for assigning the pointer to a array?

  Was this answer useful?  Yes

Avi

  • Aug 24th, 2016
 

That is because when you declare an array say--->int arr[3]={1,2,3};
arr itself contains the base address of the array i.e arr is equivalent to &arr[0]
so if a pointer say int *ptr is to point an array arr the ptr=arr is same as ptr=&arr[0]
But ptr=&arr is not valid in some compilers because arr is itself a pointer so &(pointer variable) is ambiguous! But in Linux it is most probable You will not get this error

  Was this answer useful?  Yes

Ankit Singh

  • May 16th, 2017
 

As before or in terms of other site definition generic pointer is like a void pointer but here you are saying generic pointer can not hold the address of any datatype . why? please explain ....

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

Answer Question

Click here to Login / Register your free account


 
Send   Reset

 

Related Answered Questions

 

Related Open Questions