简体   繁体   中英

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?

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM