dYNAMIC MEMORY- need help!!!

Hello!
Please, let's go from the beginning!!!

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52


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;
}

Output:

1  Now main starts
2  Adress of the array a is: 0x8051438
3
4
5  Adress of the array a is: 0x80514f0
6
7
8  main: 0x80514f0
9  15 20 23
10 0x8051438 0x805143c 0x8051440
 



In the line 29, adress of the array (a[0]), is obviously 0x8051438
.
Please, which line in the program causes output line 5?
Array a has obviously ANOTHER adress there.


MANY THANKS!!!






Last edited on
Every time you call po(), it'll execute all the code in po(), which includes writing that line (and allocating memory that the caller is expected to free).

You call it twice; lines 29, 31.
Hello!
Output line 5 cannot be caused by line 31 in program, cause line 31 in program causes line 8 in output!!!


That is why I worte text- to avoid mistakes!
On line 35:1) function po() gets called and in function, on line 20 it outputs address of newly created array on screen (output line 5)
2) function po() returns value to main():31 and output statement prints return value to screen (output line 8)
Topic archived. No new replies allowed.