2017-07-01 125 views
0

我需要編寫一個C函數,從用戶獲取他想要輸入的單詞的數量,然後該函數必須從用戶那裏掃描單詞,但它們在陣列。函數獲取單詞並將它們放在數組中

例如:

程序:

number of words: 

用戶:

3 
hi 
my 
name 

(每字之間有輸入),則函數必須把這些詞語的 字符串數組(數組的大小必須由malloc定義,並且字符串的最大大小爲100(可能更小))。

int main() 
{ 
    int n; 
    printf("Please enter the number of words: \n"); 
    if (scanf("%d",&n)!=1) 
     return 0; 
    char *name; 
    name = malloc((sizeof(char)*100*n)); 
    int c; 
    int i; 
    int m; 
    for (i = 0; i < n && ((c=getchar()) != EOF);i++) 
    { 
     name[i] = c; 
    } 
    finds_themin(&name, m); //I know this work 
    return 0; 
} 
+1

這聽起來像一個任務。你試過什麼了? – x29a

+0

@ x29a我把代碼 我認爲我寫的代碼是錯誤的 – STD

+0

在stackoverflow.com上,有很多關於這種相同類型的任務的問題的實例。建議使用stackoverflow.com搜索引擎來公開這些類型的問題並檢查相應的答案 – user3629249

回答

0

您需要設置指針指針。

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

int main(){ 

    char **s; 
    int n; 
    char buffer[64]; 
    fgets(buffer,64,stdin); 
    n=strtol(buffer,NULL,10);// I avoid using scanf 

    s=(char **)malloc(sizeof(char*)*n);// you need to declare a pointer to pointer 

    /* 
     'PtP s' would look like this: 
     s[0]=a char pointer so this will point to an individual string 
     s[1]=a char pointer so this will point to an individual string 
     s[2]=a char pointer so this will point to an individual string 
     .... 

     so you need to allocate memory for each pointer within s. 
    */ 
    int i; 
    for(i=0;i<n;i++){ 
     s[i]=(char*)malloc(sizeof(char)*100);// length of each string is 100 in this case 
    } 

    for(i=0;i<n;i++){ 

     fgets(s[i],100,stdin); 

     if(strlen(s[i])>=1){// to avoid undefined behavior in case of null byte input 
      if(s[i][strlen(s[i])-1]=='\n'){ // fgets also puts that newline character if the string is smaller than from max length, 

       s[i][strlen(s[i])-1]='\0'; // just removing that newline feed from each string 
      } 

      else{ 

       while((getchar())!='\n'); //if the string in the command line was more than 100 chars you need to remove the remaining chars for next fgets 
      } 
     } 
    } 

    for(i=0;i<n;i++){ 
     printf("\n%s",s[i]); 
    } 
    for(i=0;i<n;i++){ 
     free(s[i]); //avoiding leaks 
    } 
    free(s); 
} 
0

當你需要存儲一個字符串數組,你需要的char*char**陣列指向每個字符串(字符數組)。

char **name; 
name = malloc(n); // to store n strings. 

然後在循環中使用fgets來讀取輸入爲一行。此外,您需要爲每個新的char陣列分配內存。

fflush(stdin); 
for (i = 0; i < n; i++) { 
    name[i] = malloc(100); // allocating memory for string. 
    fgets (name[i], 100, stdin); // 100 is the max len 
} 

然後,您可以簡單地在char**陣列迭代中,i個指標將指向i個字符串。

for (i = 0; i < n; i++) { 
    // printf("%s", name[i]); 
} 
相關問題