#include <iostream>
using namespace std;
class B
{
int a = 10;
int b = 20;
int A[5] = {1, 2, 3, 4, 5};// int *A = new int[5]{1, 2, 3, 4, 5};
public:
friend void change(B);
void print()
{
for (int i = 0; i < 5; i++)
{
cout << " " << A[i];
}
cout << endl;
}
};
void change(B obj)
{
int *p = obj.A;
for(int i = 0; i < 5; i++)
{
*p += 10;
p++;
}
}
int main()
{
B first;
first.print();
change(first);
first.print();
change(first);
first.print();
return 0;
}
Here, A
is holding the base address of the array, and when I am calling the function change()
then a pointer (p
) in the function is holding the address of the address of A
that is in the base class. So, I think that it should change the value of the data of the object in the array, and it should print the value as:
1 2 3 4 5
11 12 13 14 15
21 22 23 24 25
But it's not going like that, it is printing this:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
But, when I am making the array on the heap using int *A=new int[5]{1, 2, 3, 4, 5};
then it works as I expect.
So, how will I know when the value of the data will change and when the data will not change? In both cases, A
has the pointer to the address of the original array, but in the one case it is changing the value, while in the other case it's not changing, Why? Please explain to me in detail.