c++ program:unexpected output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<iostream>
using namespace std;



struct elem{
int a;
int b;
};

void display(elem *ptr);



int main()
{
elem *ptr=new elem();
display(ptr);
return 0;

}


void display(elem *ptr1)
{  ptr1->a=5;
   ptr1->b=6;
elem*ptr2=ptr1++;
cout<<ptr1<<endl<<ptr2<<endl;
cout<<ptr2->a<<endl<<ptr2->b<<endl;
}


This simple program is giving unexpected output:
1
2
3
4
0x84ba010
0x84ba008
5
6


1.Why is it displaying 5 and 6 which are contents of ptr1 ,when I actually displayed contents of ptr2 which should have resulted in segmentation fault.

2.when it didnt lead to segmentation fault I displayed ptr1 and ptr2 and difference between those two pointers is just 2 bytes(0x84ba010-0x84ba008=2) which should be 4 bytes as elem struct has 2 integers.

please help!!

Do you realize that you have computed the difference of the pointers incorrectly? Remember the values are in hexadecimal not decimal (0x10 == 16).

And as far as your first question, welcome to the world of undefined behavior where anything can happen.

Last edited on
Topic archived. No new replies allowed.