2017-07-01 127 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]); 
} 
相关问题