2017-03-19 38 views
-1
#include <stdio.h> 

char name[99]; 

int main(){ 
    int n = 5; 
    for(int i = 0; i < n ; i++){ 
     scanf("%s", &name[i]); 
     //fflush(stdin); gets(&nama[i]); 
    } 

for(int i = 0; i < n ; i++){ 
    printf("Print %s", name[i]); 
    } 

} 

我要問我爲什麼打印該代碼時遇到錯誤,但如果我不使用索引這樣爲什麼當打印字符數組索引

for(int i = 0; i < n ; i++){ 
     printf("Print %s", name); 
     } 

可以不打印索引錯誤。

+0

它給我在運行時警告沒有錯誤..和分段錯誤.. –

+2

因爲'%s'需要一個NULL結尾的字符串,一個'字符*'的地址,但您提供的' char':'name [i]'。 –

回答

2

name是一個單獨的字符數組,而不是字符串。每個scanf正在讀入下一個位置的一個數組。在您打印的循環中,您將單個字符放入由%s使用的指針中(請注意,char是C中的整型,而不是像許多語言中的長度爲1的字符串)。

#include <stdio.h> 

// Two dimensional char array 
char name[5][99]; 

int main(){ 
    int n = 5; 
    for(int i = 0; i < n ; i++){ 
     scanf("%s", name[i]); // Decay to char* 
     //fflush(stdin); gets(&nama[i]); 
    } 

for(int i = 0; i < n ; i++){ 
    printf("Print %s", name[i]); // Decay to char* 
    } 

}