why is new int[] changing its adress???

Write your question here.

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
31
32
33
34
35
36
  
int* po(int b){
  int d1;
  d1=3*b;
  int d2;
  d2=d1+5;
  int d3;
  d3=d2+3;
  int* a=new int[3];


  //int a[3]={d1,d2,d2+3};

  a[0] = d1;
  a[1] = d2;
  a[2] = d3;


  cout<<"Adress of the field a is: "<<&a[0]<<endl<<endl<<endl;
  return a;
  }


int main(){
  cout<<"Now main starts"<<endl;
  int st=5;
  int * z;
  z=po(st);

  cout<<"main: "<<po(st)<<endl;
  cout<<z[0]<<" "<<z[1]<<" "<<z[2]<<endl;
  cout<<&z[0]<<" "<<&z[1]<<" "<<&z[2]<<endl;


  return 0;
}


Dear All!
array a[] obviously has 2 adresses in the memory.
One adress in function, another adress in main.
But, how is it possible? Should the adress not be the same?

MANY THANKS!!!
Each time when you using new x, it creates a new object x in memory. With different address, because old one is occupied.

Your program output:
1
2
3
4
5
6
7
8
9
10
11
Now main starts
Adress of the field a is: 0x2f7fb0 //first call (z=po(st);)


Adress of the field a is: 0x565b40 //second call (..."main: "<<po(st)...)


main: 0x565b40 //Result of a second call
15 20 23
0x2f7fb0 0x2f7fb4 0x2f7fb8
//↑↑↑Result of a first call 
It doesn't. You're misreading the output.


I got this output from IDEone:


Now main starts
Adress of the field a is: 0x8c73008


Adress of the field a is: 0x8c73018


main: 0x8c73018
15 20 23
0x8c73008 0x8c7300c 0x8c73010


The first address printed (0x8c73008) is what gets assigned to z.
And you'll notice that is the same address that is printed when you output z on the very last line

The other address (0x8c73018) is from you calling po a second time on line 30. This creates an entirely different array... which of course will have a separate address.

This separate array has nothing to do with z, though. z is still assigned according to the first po call on line 28.


EDIT: doh! ninja'd
Last edited on
Topic archived. No new replies allowed.