Why can I access a structure other than the pointer?

6

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

struct exemplo{
    int a ; 
};

int main()
{
    struct exemplo *p;

    p->a = 10 ;    
}
    
asked by anonymous 22.12.2015 / 22:24

1 answer

6

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

The code has flaws. It even works, but may not do what you expect. It is necessary to 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);
    return 0;
}

See running on ideone .

Does not that look better?

If you do not want to declare the variable for the structure, you can also do it, but there you have to be explicit for any use of it, see how . Credits to carlosfigueira for commenting on this.

If you really want to put the structure in the stack (do not use malloc() , then do not 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);
    return 0;
}

See running on ideone .

It is possible to boot with pointer as well.

    
22.12.2015 / 22:36