Search code examples
cpointersoperator-precedencedereference

How can I fix "error: 'a' is a pointer; did you mean to use '->'?" when attempting to run my C code?


This is the code I tried to run:

#include <stdio.h>

struct cow{
  int moo;  
};

void newm(struct cow *a){
    *a.moo = 5;
}

int main() {
    // Write C code here
    printf("Hello world");
    struct cow a;
    newm(&a);
    printf("hallo %i", a.moo);
    

    return 0;
}

When running the code I get the following error message:

gcc /tmp/2RZ9WOHWdH.c -lm
/tmp/2RZ9WOHWdH.c: In function 'newm':
/tmp/2RZ9WOHWdH.c:9:9: error: 'a' is a pointer; did you mean to use '->'?
    9 |     *(a).moo = 5;
      |         ^
      |         ->

How can I fix "error: 'a' is a pointer; did you mean to use '->'?" when attempting to run my C code?


Solution

  • In this expression

    *a.moo = 5;
    

    it is supposed that the data member moo is a pointer that is dereferenced.

    But actually it is a that is a pointer.

    The postfix member access operator . has a higher precedence than the unary operator *.

    So instead you need to write either

    a->moo = 5;
    

    or

    ( *a ).moo = 5;