Why can I access a structure without the pointer?

Asked

Viewed 123 times

6

When I declare a pointer to struct I can access members without entering an address struct, why is it possible? For example:

struct exemplo{
    int a ; 
};

int main()
{
    struct exemplo *p;

    p->a = 10 ;    
}
  • I didn’t understand the doubt, you’re putting, the address is p. has an error in this code, it works by coincidence, but nothing to do with your doubt.

1 answer

6


The operator -> is the pointer access of a member of a structure. It is syntactic sugar for (*p).a, in the shown example.

The code has flaws. It even works, but may not do what you expect. Missing declare the type for the structure (the code gets cleaner) and allocate memory to accommodate it. The correct code would be:

#include <stdio.h>
#include <stdlib.h>
typedef struct {
   int a;
} Exemplo;

int main(void) {
    Exemplo *p = malloc(sizeof(Exemplo));
    p->a = 10;    
    printf("valor = %d", p->a);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

It doesn’t get better this way?

If you do not want to declare the variable for the structure, you can also do it, but then you have to be explicit for all use of it, see how. Credits to the Carlosfigueira for having commented on this.

If you really want to put the structure on stack (not use malloc(), so don’t use pointer:

#include <stdio.h>
typedef struct {
   int a;
} Exemplo;

int main(void) {
    Exemplo p = { 10 };
    printf("valor = %d", p.a);
    Exemplo p2 = { .a = 10 }; //apenas uma variação
    printf("valor = %d\n", p2.a);
    Exemplo p3;
    p3.a = 10; //outra variação
    printf("valor = %d\n", p3.a);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

It is possible to initialize with pointer as well.

  • Just one detail: you don’t necessarily have to declare the type for the structure. Without the Exemplo above, the structure already has a type (struct exemplo), that you can use in malloc: malloc(sizeof(struct exemplo)).

  • @carlosfigueira yes, really possible, I will add this. I had already made a modification because I ended up reversing the intention.

Browser other questions tagged

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