Why can not I access the data of this struct with the dot, only with the arrow?

1

I have alloted this struct by dynamic allocation and can only access the data idade via arrow and not by point wanted to know why?

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

struct pessoa
{
   int idade;
};

void alteraIdade(struct pessoa *l);

int main(int argc, char** argv)
{
   struct pessoa *jose = malloc(sizeof(int));
   alteraIdade(jose);
   printf("%d\n", jose->idade);
   free(jose);
   return 0;
}


void alteraIdade(struct pessoa *l)
{
    l->idade = 90;
}
    
asked by anonymous 21.12.2018 / 23:19

1 answer

5

Because it is accessed through a pointer, then you need to derrefer the pointer before accessing the member.

jose is a pointer to an object and not the object itself, it is a number with the address. To get the object itself you have to say that you want it, using the * operator and then with the object you can get its member. Then you need to (*jose).idade . As this is quite common they have created a simpler syntax jose->idade , which is the same thing.

    
22.12.2018 / 00:12