2017-07-01 4 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アレイのメモリを割り当てる必要があります。あなたは、単に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 
} 

i番目のインデックスはi番目の文字列を指します。

for (i = 0; i < n; i++) { 
    // printf("%s", name[i]); 
} 
関連する問題