0

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?

Eijomjo
  • 102
  • 1
  • 11
  • 1
    ask yourself what is the result of the expression `&(s1.pi1)` used to build your structure. Keep in mind that a pointer makes sense if it points to something, a pointer doesn't imply the existence of an associated object. – user2485710 Jan 11 '14 at 19:04
  • 1
    Maybe `S s1 = { 5 , &(s1.i1) };`? – Marian Jan 11 '14 at 19:05
  • `s1.pi1` _does_ access the "pointer member data of struct". Curiously it appears the value `s1.pi1` is initialized with its address. – chux - Reinstate Monica Jan 11 '14 at 19:08
  • Yes i know i typed wrong. Though i still get the same result when i run it. – Eijomjo Jan 11 '14 at 19:11
  • It was as you said i think. When i edited the code correctly and used *(s1.pi1) it worked! Sorry this is the second post i mess up. But i am very thankful for your answers! It helped me solve the problem. – Eijomjo Jan 11 '14 at 19:19
  • @Eijomjo well, **what** do you expect the output to be? –  Jan 11 '14 at 19:49

2 Answers2

3

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;
}
godel9
  • 7,340
  • 1
  • 33
  • 53
1

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.

Community
  • 1
  • 1
Gil
  • 1,518
  • 4
  • 16
  • 32