Struct member access error passed by reference

Asked

Viewed 2,590 times

0

I have the code below that has a function to define the salary = 4000, but it returns me the following error:

[Error] request for Member 'salario' in Something not a Structure or Union

The error occurs in the line I try to define the salary. I am using parameter passage by reference, because passing parameter by value does not change the salary of Joao, because the changes only occur within the function, not reflected in his salary.

#include <stdio.h>
#include <stdlib.h>

typedef struct{
    int idade;
    int salario;
}PESSOA;

void setSalario(PESSOA *p){
    *p.salario = 4000;
}

int main(int argc, char *argv[]) {

    PESSOA joao;

    setSalario(&joao);

    printf("Salario do joao: %d",joao.salario);
}

2 answers

4


It is a mere matter of operators' precedence. The operator . takes greater precedence over the * unary. So:

*p.salario

Is read as:

*(p.salario)

And how p it’s not a struct, it’s a pointer to a, you can’t write p.salario.

Can correct using parentheses:

(*p).salario

Or rather, use the -> to read fields from a pointer to struct:

p->salario
  • Thank you very much William

  • I hit my eye and already saw, but Guilherme was faster ;p

0

I found the problem.

In the line I define the salary:

 *p.salario = 4000; // errado
(*p).salario = 4000; // correto

Browser other questions tagged

You are not signed in. Login or sign up in order to post.