function and main adresses starting from same point?

Hello!
please, is it possible to achieve that first run of po* and second one (from main) give same addresses?- if it is easy!!!



//(both are ment to give addresses of some array elements). ;)



if not, please, just tel lme it is not easy- and I will spend time on it later!!!
many thanks!!!!

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
   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<<"***"<<&a[0]<<" "<<&a[1]<<" "<<&a[2]<<endl<<endl<<endl;

return a;
}


int main(){
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;
}
Last edited on
When the operator new is used, there is no way to be sure what actual address will result. However, because there is no delete [] between the first and second use of new, the two addresses have to be different, as the first block of memory is still in use, so of course a different address will result the second time.

You could (and indeed should) release the memory when it is no longer in use, or the program will have a memory leak.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int main()
{
    int st=5;
    int * z;
    
    // first time
    z=po(st);
    cout << "main 1" << endl;
    cout<<z[0]<<" "<<z[1]<<" "<<z[2]<<endl;
    cout<<&z[0]<<" "<<&z[1]<<" "<<&z[2]<<endl;
    
    delete [] z;  // release the block of memory
    z =  NULL;    // set the pointer to NULL as that address is no longer valid.
    
    // second time
    z=po(st);
    cout << "main 2" << endl;
    cout<<z[0]<<" "<<z[1]<<" "<<z[2]<<endl;
    cout<<&z[0]<<" "<<&z[1]<<" "<<&z[2]<<endl;
    
    delete [] z;  // release the block of memory
    z =  NULL;    // set the pointer to NULL as that address is no longer valid.
    return 0;
}
Topic archived. No new replies allowed.