Home > Software design >  Getting an error for this simple code I'm using. I bet the solution is very simple but I can�
Getting an error for this simple code I'm using. I bet the solution is very simple but I can�

Time:11-22

This is the code I tried to run (have a C assignment I'm working on but this is just to help me understand the syntax with pointers in C.)

#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;
      |         ^
      |         ->

CodePudding user response:

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;
  • Related