jeudi 2 novembre 2017

C++ Structure memory assignment and comparison

In the following program,

//1 and //2 are NOT working, but //3 is working.

//4 and //5 are NOT working, but //6 is not working.

Question:

If address values are same in if condition, why comparison is giving following error:

error: comparison between distinct pointer types 'Node*' and 'int*' lacks a cast*

#include<iostream>
using namespace std;

struct Node  
{
    int data;
    Node *Next;
};

int main()
{
    Node *Node1=new Node;
    Node *Node2=new Node;

    Node1->data=11;
    Node1->Next=Node2;

    Node2->data=22;
    Node2->Next=NULL;

    /* 
    if(Node1->Next==&Node2->data) //1
        cout<<"Node1->Next==&Node2->data"<<endl; //2
    */        
        cout<<"Node1->Next="<<Node1->Next<<"  &Node2->data="<<&Node2->data<<endl;//3 

    /*    
    if(Node2==&Node2->data) //4
        cout<<"Node2==&Node2->data"<<endl; //5
    */   
        cout<<"Node2="<<Node2<<"   &Node2->data="<<&Node2->data<<endl; //6

    if(Node1->Next==Node2)  //7
        cout<<"Node1->Next==Node2"<<endl;  //8 

        cout<<"Node1->Next="<<Node1->Next<<"   Node2="<<Node2<<endl; //9
}

--

**Output:**
Node1->Next=0x7fb05c460e00  &Node2->data=0x7fb05c460e00
Node2=0x7fb05c460e00   &Node2->data=0x7fb05c460e00
Node1->Next==Node2
Node1->Next=0x7fb05c460e00   Node2=0x7fb05c460e00

Aucun commentaire:

Enregistrer un commentaire