Why can’t I access the data from this struct with the dot, just with the arrow?

Asked

Viewed 51 times

1

I allotted that 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;
}

1 answer

5


Because it is accessed through a pointer, then you need to bypass 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 catch the object itself you have to say that you want this, using the operator * and then with the object you can catch his member. So you need to do (*jose).idade. As this is quite common they have created a simpler syntax jose->idade, which is the same thing.

Browser other questions tagged

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