c - 函数获取单词并将它们放入数组中

标签 c arrays string function

我需要编写一个 C 函数,从用户那里获取他想要输入的单词数,然后该函数必须扫描用户的单词以及数组中的单词。

例如:

程序:

number of words:

用户:

3
hi
my
name

(每个单词之间有 Enter)然后函数必须将这些单词放入 字符串数组(数组的大小必须由 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;
}

最佳答案

您需要设置一个指向指针的指针。

#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);
}

关于c - 函数获取单词并将它们放入数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44859765/

相关文章:

c - 如何在 C 中强制崩溃,取消引用空指针是一种(相当)可移植的方式吗?

c - Microsoft C 运行时中的 msvcp140_1.dll 和 msvcp140_2.dll 文件是什么?

C - 以可变大小打印流数组字节

php - 如何在 PHP 中使用 COM 对象获取 UTF-8 字符串?

regex - Excel VBA 正则表达式检查重复字符串

string - 在 Rust 中加入字符串向量

c - 使用 Makefile 链接多个文件

C:定义函数,它接受常量字符串数组,返回随机选择的一个

javascript - JS数组查找和替换?

java - 将字符串 (Last\First\tAg) 转换为包含元素 {Last, First, Age} 的数组