Reputation: 3465
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..
Upvotes: 0
Views: 612
Reputation: 108978
temp
is local to the function enterSentence
. 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 temp
a static object that can live since the program started till it ends
static char temp[999];
Note: static
is a quick and dirty solution, as I said. It is mostly better avoided.
Edit
Slow and clean solution: move the temp
object to the calling function and pass its pointer to the function
int main(void) {
char temp[999];
/* ... */
enterSentence(temp, sizeof temp);
/* ... */
}
size_t enterSentence(char *dst, size_t len) {
size_t retlen;
fgets(dst, len, stdin);
retlen = strlen(dst);
if (dst[retlen - 1] == '\n') dst[--retlen] = 0;
return retlen;
}
Upvotes: 5