Eijomjo
Eijomjo

Reputation: 102

Accessing pointer member data of struct

I am trying to access the data of a pointer that is a member of a struct.

typedef struct
{
    int i1;
    int* pi1;
} S;


int main()
{
    S s1 = { 5 , &(s1.i1) };

    printf("%u\n%u\n" , s1.i1 , s1.pi1 ); //here is the problem 

return 0;
}

The problem lies in the second argument of printf. When i run the program i get the following result in console: 5 ...(next line) 2381238723(it's different every time). This is correct, and the result is not unexpected. I have tried things like:

*(s1.pi1) 

and

s1.*pi1

None of them works. Is there any operator in C or method to do this?

Upvotes: 0

Views: 144

Answers (2)

Gil
Gil

Reputation: 1538

Going through godel9's suggestion and comments, I infer that you have found a way to get the expected results

You wrote: I have tried things like:

*(s1.pi1) and s1.*pi1

I sense a li'l confusion there.

mystruct.pointer means that you have access to the pointer, now give,take,compare.. address.

*(mystruct.pointer) means that you have dereferenced the pointer,now giv, take,increment.. value.

Remember that pointers are just variables which store addresses(!) but more versatile than the common ones.

Upvotes: 1

godel9
godel9

Reputation: 7390

I'm guessing here, but I think you might have meant to do the following:

typedef struct
{
    int i1;
    int* pi1;
} S;


int main()
{
    // Take the address of s1.i1, not s1.pi1
    S s1 = { 5 , &(s1.i1) };

    // Dereference s1.pi1
    printf("%u\n%u\n" , s1.i1 , *s1.pi1 );

    return 0;
}

Upvotes: 3

Related Questions