Can void pointers be dereferenced?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rahul sinha
    New Member
    • Jan 2011
    • 17

    Can void pointers be dereferenced?

    Code:
    #include<stdio.h>
    #include<conio.h>
    
    void main()
    
    {
    void *ptr;
    char *a='A';
    char *b="TAN";
    int i=50;
    ptr=a;
    ptr=(char*)malloc(sizeof(a));
    printf("%c",*ptr);
    ptr=i;
    ptr=(int*)malloc(sizeof(i));
    printf("%d",++(*ptr));
    ptr=b;
    ptr=(char*)malloc(sizeof(b));
    printf("%c",++(*ptr));
    getch();
    }
    On compilation error, was we cant derefrence the void pointer but avoid pointer can point to any other pointer type. So after we have assigned a void pointer to say a pointer of type int, then we should be able to dereference the pointer no? I am not able to get this behavior.
    Last edited by Niheel; Jan 27 '11, 05:21 AM. Reason: Use proper grammar and punctuation. Your posts are hard to read. If we have to edit any more your account will be suspended.
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    The compiler does not know the type of what the void pointer points at, thus you can't dereference a void pointer. C does not support variant data types (where the type of the item is determined at run time).

    What are you trying to accomplish?

    Comment

    • rahul sinha
      New Member
      • Jan 2011
      • 17

      #3
      hey donbock i got it now that compiler doesn't know the type of variable to which a void pointer is pointing..but what i thought that,since void can point to any variable type so if we assign a void pointer to any pointer of some other type like :
      {
      void *p;
      int *p1;
      *p1=5;
      p=p1;
      /*now p points to p1(an integer type))*/
      /*so*/
      printf("%d",*p) ;/*will this statement work*/
      }
      so i am having this doubt....that is this the way to
      dereference a void pointer...

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        No. The assignment operator transfers the value of p1 to p but it does not change the type of p. p is still a void pointer.

        The assignment does work in the other direction:
        Code:
        int a;
        void *p;
        int *p1;
        ...
        p = &a;
        p1 = (int *)p;
        *p1 = 10;
        The cast on line 6 is optional in C, but it is required for C++.

        Comment

        Working...