How to draw a pointer without assignment in C?

I have type pointers void *

, but I know they actually point to a structure. When I assign their casting to a different pointer and use it then everything works fine, but I cannot directly use the void cast pointer.

Here's an example:

typedef struct {
    int x1;
    int x2;
} TwoX;

main()
{
   void * vp;
   TwoX xx, *np, *nvp;
   xx.x1 = 1;
   xx.x2 = 2;

   vp = (void *)&xx;
   np = &xx;
   nvp = (TwoX *)vp;
   printf ("test normal pointer: %d %d\n", np->x1, np->x2);
   printf ("test recast void pointer: %d %d\n", nvp->x1, nvp->x2);
   //printf ("test void pointer: %d %d\n", (TwoX *)(vp)->x1, (TwoX *)(vp)->x2); // this line doesn't compile

}

      

The last line printf

doesn't compile and I get the following error and warning twice (one for each casting):

warning: dereferencing void * pointer [enabled by default]
error: request for member x1 in something not a structure or union

      

Without this line, everything works, and the output is:

test normal pointer: 1 2
test recast void pointer: 1 2

      

How can I draw a pointer void *

without assigning it to a new variable?

+3


source to share


2 answers


In your code, change

printf ("test void pointer: %d %d\n", (TwoX *)(vp)->x1, (TwoX *)(vp)->x2);

      

to

printf ("test void pointer: %d %d\n", ((TwoX *)(vp))->x1, ((TwoX *)(vp))->x2);
                                      ^            ^      ^            ^
                                      |            |      |            |

      



Without an extra pair of parentheses, the dererence operator ->

takes precedence over typecasting, so (Two *)

it is not valid until dereferencing.

By logic, you cannot dereference a type pointer void

. This is why the warning. Then, when you request access to any member variable of a structure pointer, the pointer is assumed to be of the type of that structure, which does not happen (since it is still a type void

), hence the error.

You can check operator priority here .

+4


source


I think this is just the order of operations. Try it ((TwoX*)vp)->x1

. Note that the cast and pointer are grouped together with parentheses.



+3


source







All Articles