1

In my sample code below:

#include <stdlib.h>
#include<stdio.h>    
int main()
{

  typedef struct {float x; float y;}C;

  C z;

  z.x=4;
  z.y=6;

  C *zpt=&z;

  *zpt.x;

  printf("%f",(*zpt).x);
}

I know (*zpt).x or zpt->x is used to dereference the pointer. But I get an error when I use *zpt.x, Error - "request for member 'x' in something not a structure or union". Can someone explain what does *zpt.x do? Is this an valid syntax and if yes, where and how it should be used?

Arnold
  • 185
  • 1
  • 2
  • 8

2 Answers2

4

this goes wrong *zpt.x;

becuase it is interpreted as

*(zpt.x)

which has no meaning. First there is no zpt.x, second even if that was a float somehow you can't use * on a float

this is why the -> operator exists: zpt->x is the same as (*zpt).x but easier to read and type

pm100
  • 48,078
  • 23
  • 82
  • 145
4

The error you get is this:

error: request for member ‘x’ in something not a structure or union

As the compiler informs you, zpt is neither a structure or a union. The problem is that precedence of the dot operator (.) is higher than the one of the asterisk (*), thus the dot is enabled first and as a result you get the error, since the compiler reads this as: *(zpt.x).

From C Operator Precedence

Precedence 1: . Structure and union member access

Precedence 2: * Indirection (dereference)

Putting parentheses makes clear how you want the operators to work, so

(*zpt).x

will work just fine, but you will receive a warning like this:

warning: statement with no effect [-Wunused-value]

because you don't do anything, but I know this is just test code.


I would suggest reading the relevant question:

Why does the arrow (->) operator in C exist?

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305