How to access a pointer within a pointer structure

Asked

Viewed 242 times

2

I know that to access a normal variable within a pointer structure I can use this syntax:

struct teste { 

    int valor;
    int *aponta;

};

struct teste testando, *testado;
testado = &testando;
testado -> valor = 10;

However, how to access the pointer aponta which is contained in the structure, using the pointer testado?

1 answer

4


To make that pointer point somewhere:

int teste2 = 123;
testado->aponta = &teste2;

To change the value of what is pointed:

*(testado->aponta) = 456;

And to read the variable value:

*(testado->aponta)

See here a test with the full code:

#include <stdio.h>

struct teste { 
    int valor;
    int *aponta;
};

int main() {

    struct teste testando, *testado;

    testado = &testando;
    testado->valor = 10;
    int teste2 = 123;
    testado->aponta = &teste2;
    *(testado->aponta) = 456;
    printf("%d %d", teste2, *(testado->aponta));
}

The exit is 456 456. See here working on ideone.

  • This would be an operator *(ptrStruct->member)? If so, what would his name be? I did not understand why I had to involve in parenthesis () followed by an asterisk * the structure.

  • 1

    @cat The parenthesis is used to group subexpressions. It is the same parenthesis used in 3 * (2 + 4). The unary operator * is the dereference operator and is used to access the contents of a pointer.

  • Thanks even, I did not find the answer in other places, it was almost obvious. Just add parentheses to respect the order of origin and insert the asterisk to get the reference value;

Browser other questions tagged

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