Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Acessing another structure's member through a pointer

Tags:

c

pointers

#include<stdio.h>

int main()
{
    struct node
    {
        int data;
        struct node *next;

    };

    struct node n1,n2,n3;
    int i;
    n1.data = 100;
    n2.data = 200;
    n3.data = 300;

    n1.next = &n2;
    n2.next = &n3;

    i = n1.(*next).data;
    printf("%i\n",i);

    printf("%i\n", n2.next->data);

    return 0;
}

My Question is simple. How come i am not able to access n2 node via n1 node when i use this i = n1.(*next).data; I get an error. However if i change it to i=n1.next->data

I thought (*x).y and x->y mean the same thing.

like image 383
user1010101 Avatar asked Mar 03 '26 11:03

user1010101


1 Answers

You're right, (*x).y and x->y mean the same thing, that's why you should write (*n1.next).data (equivalent to n1.next->data as n1.next is your x).

EDIT: The parenthesis are so due to the evaluation order:

  1. Take n1: n1 (a struct node)
  2. Take member next: (n1).next (a struct node *)
  3. Deference the pointer: *((n1).next) (a struct node)
  4. Take member data: (*((n1).next)).data (an int)

Read what the C11 standard says in the @Christophe answer, and notice how the . operator used in steps 2 and 4 above where used with struct node as first operands (see steps 1 and 3) and member names as seconds operands.

like image 68
ericbn Avatar answered Mar 05 '26 06:03

ericbn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!