Below code produces two smiley faces when I call case 2 after case 1 (in other words after one while loop). However printSentence(); works as it should be in case 1.
#include <stdio.h>
#include <string.h>
char *enterSentence();
void printSentence(char *);
char *sentence;
int willContinue = 1;
main() {
while (willContinue) {
int a;
scanf("%d", &a);
switch (a) {
case 1:
getchar();
sentence = enterSentence();
printSentence(sentence);
break;
case 2:
getchar();
printSentence(sentence);
break;
case 3:
willContinue = 0; //exit
break;
}
}
}
char *enterSentence() {
char temp[999];
gets(temp);
return temp;
}
void printSentence(char *asd) {
puts(asd);
}
.
. //more code
.
I wonder what is the problem here, thanks for any help..
tempis local to the functionenterSentence. It is created when the function is entered and it is destroyed when the function terminates.When you return the address of the object (
return temp;) it still exists and has that address, but it will be immediately destroyed afterwards and the calling function receives a pointer to an invalid location.Quick and dirty solution: make
tempa static object that can live since the program started till it endsNote:
staticis a quick and dirty solution, as I said. It is mostly better avoided.Edit
Slow and clean solution: move the
tempobject to the calling function and pass its pointer to the function