char* function doesn`t work

hi, I have a problem in function returning char[4] into string variabille.

Code:
1
2
3
4
5
6
7
8
char*DROP(string dropped,string equiped){
char item[4];
....
ch=getch();
    if(ch=='a') { for(i=0;i<=3;i++) item[i] = dropped[i]; }
    if(ch!='a') { for(i=0;i<=3;i++) item[i] = equiped[i]; }
return item;
}


before returning 'item' in function it had good value (f.e.: "0042")
1
2
3
4
5
6
int main(){
...
string itemid[6];
itemid[dropitemslot]=DROP(dropitem,itemid[dropitemslot]);
...
}


but now 'itemid[dropitemslot]' have value ":)___".

Please, can someone help me?? THANKS!!
When a function is executed, it's local variables cease to exist. Therefore you should never return a pointer to a local variable.
To solve this problem you could allocate item in main and pass it's pointer to DROP
or dynamically allocate a char array (with new or malloc)
but in this case the best way would be to simply use string instead of char[]

And by the way, your item was not a null terminated string, so you would have had problems anyway.
Thank you very much!!! :)
I gave there string DROP(-||-)
string item...
and it works now :)
Topic archived. No new replies allowed.