#include<iostream>
using namespace std;
int main()
{
struct node
{
int data;
struct node *next;
};
struct node *node1;
struct node node2;
node2.data = 200;
node2.next = NULL;
cout<<"address of node2: "<<&node2<<endl;
cout<<"address of node2.data: "<<&node2.data<<endl;
cout<<"address of node2.next: "<<&node2.next<<endl;
cout<<"value of node2 data: "<<node2.data<<endl;
cout<<"value of node2 next is: "<<node2.next<<endl;
node1 = (struct node*)malloc(sizeof(node));
node1->data = 100;
node1->next = NULL;
cout<<"value of node1 data: "<<node1->data<<endl;
cout<<"value of node1 next: "<<node1->next<<endl;
cout<<"address of node1 variable is: "<<&node1<<endl;
cout<<"address of node1 data variable is: "<<&node1->data<<endl;
cout<<"address of node1 next variable is: "<<&node1->next<<endl;
cout<<"value stored at node1 variable is: "<<node1<<endl;
}
I wanted to print the address of the members of a struct variable using the pointers to that structure. As it can be seen in my above code example, I have used &node1->next and &node1->data to print the addresses. It seems to be printing the correct addresses because I am able to access the values by dereferencing the address returned by &node1->next and &node1->data. *(&node1->next) and *(&node1->data) returns the values correctly.
But I do not understand how the notations "&node1-> data" and "&node1->next" are returning the address of the members of the struct variable. I accidentally discovered that &node1->data and &node1->next printed the addresses. Whereas with other notations like &node2.data and &node2.next, I was able to logically come up with the notations to print the addresses, but while using pointer to struct to print the address, I accidentally discovered them instead of being able to logically come up with the correct notation.
I want to know whether whatever I have come up with is the correct usage to print the addresses of the member variables and if yes how is it the correct representation ?
mallocin C++?