Memorising array from function

Hello!
OK, this function memorised a[0], but why did it no memorise a[1]?
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
  int* po(int b){
int d1;
d1=3*b;
int d2;
d2=d1+5;
int a[3];
a[0]=d1;
a[1]=d2;
a[2]=a[1]+3;
int* p=a;
cout<<p<<endl;
return p;
}


int main(){
int st=4;
cout<<" main: "<<po(st)<<endl;
int* h;
h=po(st);
cout<<"main: "<<*h<<endl;
int* k;
k=h+1;
cout<<k<<endl<<*k;
return 0;
}
Okay let's try to figure out what's going on:

int a[3]
creats an array inside the functions (po) Stack-Frame -> on the programs stack.
Once the function finished the allocated space is gone (together with the Stack-Frame).

From my understanding: the reason the first element of the Array is "memorised" is because it's the only Element of your array, that even after the function finished still has a pointer to it (p). (the others dont since "a" will be gone)

If you want this to work you have to allocate memory for the array on the heap (where it will stay until you call "delete []"
To do this, initialize the array this way:
int * a = new int[3];

that's all (the array Elements are simply stored somewhere else, where they won't be deleted (more precise the memory won't be free'd) when the function returns)

ps: allocating memory on the heap is slower than on the stack - just nice2know ;)
Last edited on
Hello, Glandy!
MANY THANKS, was searchign to find out sth like this:tup!!!


Last edited on
http://www.cplusplus.com/doc/tutorial/dynamic/

However, you should rather learn to use the container types from the standard library.
Just reading this...not sure all clear still
Topic archived. No new replies allowed.