Ive been faced with a problem recently that I can’t think of a good way to solve. I’m using a case structure to attempt to set attributes to a “character” that will be passed to an object constructor.
Example:
//note this is inside a function with a return type of int*
int selection;
cin >> selection;
int * iPtr;
switch(selection){
case 1:{
int anArray[6] = {8,5,2,4,250,100} // str, dex, int, luck, hp, mp
iPtr = anArray;
return iPtr;
}
//more cases and such below
The issue that I’m having is that when I return my pointer it seems to be filled with a good amount of junk, rather than the information, rather than the information that I would be expecting it to hold. Is that because the array gets destroyed at the end of the scope? If so what should I do to make this work out how I’m hoping for it to (getting a pointer with the values that I want).
Thanks!
Yes – anArray is declared on the stack. When the function exits, its stack frame is reclaimed, so it’s no longer valid to refer to that memory. If you want the array to persist, allocate it on the heap instead:
Just remember to clean it up later at some point with the corresonding
delete[].EDIT
You should prefer to use something that automatically manages resources for you, like in Praetorian’s answer, so that you don’t accidentally leak memory.