2014-10-16 63 views
0

我想寫一個簡單的程序,將用戶輸入的字符串讀入指針數組。閱讀很順利,但是當我想爲我的方法添加一個額外的參數以保存實際閱讀的字符串數量時,它會停止工作。編譯器不是非常有用,所以我決定在這裏解決我的問題。C讀取用戶輸入的數據

實際代碼:

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

void read(char**, int *); 
void write(char**); 

int main() { 
    int amount = 0; 
    int * amount_p = &amount; 
    char *pt_p[1000]; 
    read(pt_p,amount_p); 
    write(pt_p); 
} 


void read(char ** pt, int * amount) { 

    char stop[] = "STOP"; 
    char* woord; 
    int i = 0; 

    printf("Enter a word: "); 
    scanf("%70s", woord); 
    pt[i] = malloc(sizeof(char)*(strlen(woord)+1)); 
    pt[i] = strcpy(pt[i], woord); 

    i++; 

    while(strcmp(stop,pt[i-1]) != 0) { 
      printf("Enter a word: "); 
      scanf("%70s", woord); 
      pt[i] = malloc((strlen(woord)+1)*sizeof(char)); 
      pt[i] = strcpy(pt[i], woord); 
     i++;  
    } 
    *amount = i; 

} 

void write(char ** pt) { 
    int i = 0; 
    char stop[] = "STOP"; 
    while(strcmp(stop,pt[i]) != 0) {  
     printf("pt[%d]-> %s",i,pt[i]); 
     printf("X \n"); 
     i++; 
    } 

} 
+0

'char * woord;'''char woord [71];' – BLUEPIXY 2014-10-16 19:05:59

+0

謝謝!這似乎確定了它。但是我不完全明白爲什麼。當我聲明char * woord並不意味着我可以輸入儘可能多的字符,因爲字符串的大小尚未定義。因爲稍後我只是接受這個詞的長度,以便在pt [i]中保留足夠的空間。難道這可能是woord在記憶中的地位是未知的嗎? – Actaeonis 2014-10-16 19:16:06

+0

需要存放角色的區域。 – BLUEPIXY 2014-10-16 19:19:17

回答

2

您需要分配一些空間,可以在其中輸入字符串

char* woord;剛剛宣佈指向無處特別的指針。

代替它聲明爲

char woord[128]; 

到堆疊您的輸入上分配128個字節。

也使用fgets()代替scanf()閱讀字符串,這樣就可以防止用戶輸入過大的字符串。

if (fgets(woord, sizeof(wooord), stdin) != NULL) 
{ 
    char* p = strchr(woord, '\n'); 
    if (p != NULL) 
    { 
    *p = '\0'; 
    } 
} 
+0

謝謝!在提醒之前,它確實引起了我的注意,因爲fgets對於這項操作是一種更安全的方法。 – Actaeonis 2014-10-16 19:39:37