2015-11-01 78 views
-6

所以這是我的代碼所做的:簡單的C代碼總是崩潰

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
char playerName; 
int playerAge; 

printf("What's your name, and your age?\nYour name: "); 
scanf("%s\n", playerName); 
printf("Your age: "); 
scanf("%d\n", &playerAge); 
printf("Okay %s, you are %d years old!", playerName, playerAge); 

return 0; 
} 

每次我運行它,我輸入我的名字它崩潰,我不知道如何解決它之後。當它關閉時,出現這3件事:

format '%s' expects argument of type 'char *', but argument 2 has type 'int' [-Wformat]| 

format '%s' expects argument of type 'char *', but argument 2 has type 'int' [-Wformat]| 

'playerName' is used uninitialized in this function [-Wuninitialized]| 

我的錯誤是什麼?

+1

爲什麼你試圖將一個字符串存儲在類型'char'的變量? – fuz

+1

編譯器正在告訴你什麼。 – melpomene

+0

這些都在錯誤信息中。對於'playerName'你有'char'而不是'char *'。你需要聲明爲'char * playerName'。 – Arc676

回答

1

scanf("%s\n", playerName);是錯誤的,因爲%s呼籲char*數據,但playerName這裏鍵入char

您必須製作playerName字符數組並設置最大輸入長度以避免緩衝區溢出。

#include <stdio.h> 
#include <stdlib.h> 

int main(void) 
{ 
    char playerName[1024]; 
    int playerAge; 

    printf("What's your name, and your age?\nYour name: "); 
    scanf("%1023s\n", playerName); /* max length = # of elements - 1 for terminating null character */ 
    printf("Your age: "); 
    scanf("%d\n", &playerAge); 
    printf("Okay %s, you are %d years old!", playerName, playerAge); 

    return 0; 
}