I have two pointers with the same type pointing to the same address but the values are different. which seems quite weird to me.
- Is it due to an undefined behavior?
- Could the program lying us about the addresses?
#include <iostream>
int main()
{
int* array = new int[]{1,2,3,4,5};
int* p = array;
//delete[] array;
array = new int[]{6,7,8,9,10};
for(int i=0; i<5; i++)
{
std::cout << &(array[i]) << " => " << array[i] <<'\n';
std::cout << &(p[i]) << " => " << p[i] <<'\n';
std::cout << "--------------------\n";
}
}
when commenting the ‘delete[] array’, the output will be:
0x55763f7bc2d0 => 6
0x55763f7bc2b0 => 1
--------------------
0x55763f7bc2d4 => 7
0x55763f7bc2b4 => 2
--------------------
0x55763f7bc2d8 => 8
0x55763f7bc2b8 => 3
--------------------
0x55763f7bc2dc => 9
0x55763f7bc2bc => 4
--------------------
0x55763f7bc2e0 => 10
0x55763f7bc2c0 => 5
--------------------
when not commenting, the values are equal of course.
>Solution :
Welcome to c++! Nothing strange is going on at all. The output shown is exactly what one might expect.
When a new array is created it returns a pointer to the first element. When the first array is created, the variable array points to the 1. Then the variable p is created and set equal to array so at that point the variables both have the same value and they both point to 1.
Next, a new array is created and the pointer value is assigned to the variable array which then points to the 6. The variable p has not changed and still points to the 1.
Looking at the addresses of &(array[i]) and &(p[i]) you can see they are different as expected. Although the b and the d look very similar and I had to stare at it for a minute to realize that they were different.