2015-05-08 89 views
2

我想通過在函數中使用scanf()來獲取輸入字符串,但它保持失敗,我不知道爲什麼。掃描字符串輸入保持失敗

這是我的代碼的一部分。

typedef struct node {   
    int id; 
    char * name; 
    char * address; 
    char * group;  
    struct node * next; 
} data; 

void showG(data * head) { 
    char * n = ""; 
    int i = 0; 
    data * current = head; 
    scanf("%s", n); 
    printf("The group of %s is\n", n); 

    while (current != NULL) { 
     if (0 == strcmp(current->group, n)) { 
      printf("%d,%s,%s\n", current->id, current->name, current->address); 
      i = 1; 
     } 

     current = current->next; 
    } 
    if (0 == i) { 
     printf("no group found"); 
    } 
} 
+0

對不起,如果我將n更改爲「1」並刪除scanf的句子,另一部分將工作,這意味着它將printf「1的組是......」的東西,但如果我保持scanf並運行程序,它會停止,當我想輸入更改n的值 – YoarkYANG

回答

5

在代碼中,

char * n = ""; 

使得n指向一個字符串文字它通常放置在只讀存儲器區域,所以不能被修改。因此,n不能用於掃描另一個輸入。你想要的,什麼是下面任

  • 一個char陣列,像

    char n[128] = {0}; 
    
  • 指針char適當的內存分配。

    char * n = malloc(128); 
    

    請注意,如果你使用malloc(),後n使用結束後,你需要free()內存,也避免內存泄漏。

注:修復上述問題後,改變

scanf("%s", n); 

scanf("%127s", n); 

如果分配是128字節,以避免內存溢出。

+0

我想第二個 – YoarkYANG

+0

@unwind感謝先生的修復,不知何故,我忽略了它。 :-) –

+0

@Josephyang然後採取第二個。 :-) –