dereferencing void pointers by typecasting

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sritejv
    New Member
    • Mar 2008
    • 9

    dereferencing void pointers by typecasting

    Hello everyone,

    I am having a problem with typecasting void pointers.I have read the pointer basics but still cant understand why the following test code doesnt work.

    void *xyz;

    struct abcd
    {
    int a;
    };

    struct abcd a,*ptra;
    ptra=&a;
    xyz=(struct abcd *)ptra; //doesnt work but no error shown.
    .
    .
    printf("%d \n",xyz->a);

    }

    warning: dereferencing void * pointer (obviously,type casting didnt work)

    error : request for member a in something not a structure or union;

    Am i missing some pointer concepts here?


    Thanks,
    Sritej
  • newb16
    Contributor
    • Jul 2008
    • 687

    #2
    Originally posted by sritejv
    Hello everyone,

    I am having a problem with typecasting void pointers.I have read the pointer basics but still cant understand why the following test code doesnt work.

    void *xyz;

    struct abcd
    {
    int a;
    };

    struct abcd a,*ptra;
    ptra=&a;
    xyz=(struct abcd *)ptra; //doesnt work but no error shown.
    .
    .
    printf("%d \n",xyz->a);

    }
    Information about structure type is not stored in pointer, pointer is just an address.
    So when you write xyz->a compiler has no idea on what ->a is and what is its offset within memory block pointed by xyz

    Code:
    ptra=&a;
    xyz=ptra; // no need to typecast here
    printf("%d \n",((struct abcd *)xyz)->a);
    where (struct abcd *)xyz is of type "struct abcd*" and can be used as an argument to ->

    Comment

    • sritejv
      New Member
      • Mar 2008
      • 9

      #3
      thanks a lot for the correction..
      so initial declaration of pointer is taken into account while dereferencing so that offsets can be computed .Thats why typecasting is done while dereferencing.

      Thanks,
      Sritej

      Comment

      • AmeL
        New Member
        • Oct 2008
        • 15

        #4
        Code:
        void *xyz;
        struct abcd
        {
        int a;
        };
        struct abcd a,*ptra;
        ptra=&a;
        xyz=(struct abcd *)ptra; //doesnt work but no error shown.
        .
        .
        printf("%d \n",xyz->a);
        }
        Let review your code a bit more!!!
        You declared xyz as a pointer to void.
        Then after you do like :
        xyz = (struct abcd *)ptra; that ptra's type is a pointer to struct abcd.
        This instruction means you're trying to typecast from struct abcd pointer to struct abcd pointer ( again ) and trying to assign that to xyz that was declared as pointer to void.

        Thanks
        /AmeL

        Comment

        Working...