簡體   English   中英

C控制台應用程序循環后顯示笑臉

[英]C console application gives smiley face after loop

當我在case 1之后調用case 2 (換句話說,在while循環之后)時,下面的代碼產生兩個笑臉。 但是printSentence(); 可以在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
 .

我想知道這里是什么問題,謝謝您的幫助。

temp在函數enterSentence局部的。 它是在輸入功能時創建的,在功能終止時會被銷毀。

當您返回對象的地址( return temp; )時,它仍然存在並具有該地址,但是此后它會立即被銷毀,並且調用函數會收到指向無效位置的指針。

快速又骯臟的解決方案:將temp一個靜態對象,該靜態對象自程序啟動到結束就可以存在

static char temp[999];

注意:正如我所說, static是一種快速而骯臟的解決方案。 最好避免。


編輯

緩慢而干凈的解決方案:將temp對象移至調用函數並將其指針傳遞給該函數

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;
}

sentence存儲的先前值保持原樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM