【问题标题】:How to add a string from user input into an array dynamically in C?如何在C中动态地将用户输入的字符串添加到数组中?
【发布时间】:2021-11-28 22:41:51
【问题描述】:

我想创建一个简单的 C 程序,在循环中,当用户输入字符串时,字符串会自动添加到数组中。我不知道如何在运行时做到这一点。任何帮助将不胜感激。

编辑:为澄清起见,这里 10 是数组的最大大小。我正在考虑用一个数字初始化数组,然后在达到最大大小(在本例中为 10)时扩展该大小(可能是乘数)。

Edit2:更具体地说,我希望第一次迭代将一个字符串添加到数组中,然后第二次迭代将另一个输入的字符串添加到数组中,依此类推。

目前我的代码如下所示:

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

int main() {
    char* strings[10];
    char *input_str;
    printf("enter a string: ")
    
    strings = malloc(sizeof(char)*10); //not sure if this is required but included anyway
    
    //run a loop here to keep adding the input string 
    fgets((char)input_str, 1024, stdin);
    
}

【问题讨论】:

  • 你事先知道数组的元素/字符串的数量吗?是10吗?或者 10 应该是数组中每个元素的大小。你需要澄清这一点。
  • 是的,作为对帖子的澄清添加了这一点!

标签: c string loops


【解决方案1】:
char* strings[10];

注意strings 是一个由十个指向char 的指针组成的不可调整大小的数组,因此当您事先不知道元素数量时,它对动态分配没有用处。

我将在char ** 上使用realloc 和模运算符来检测何时到达realloc,类似于:

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

#define MULTIPLE 10

int main(void)
{
    char **strings = NULL;
    char str[1024];
    size_t size = 0;

    while (fgets(str, sizeof str, stdin))
    {
        if ((size % MULTIPLE) == 0)
        {
            char **temp = realloc(strings, sizeof *strings * (size + MULTIPLE));

            if (temp == NULL)
            {
                perror("realloc");
                exit(EXIT_FAILURE);
            }
            strings = temp;
        }
        strings[size] = malloc(strlen(str) + 1);
        if (strings[size] == NULL)
        {
            perror("malloc");
            exit(EXIT_FAILURE);
        }
        strcpy(strings[size], str);
        size++;
    }
    for (size_t i = 0; i < size; i++)
    {
        printf("%s", strings[i]);
        free(strings[i]);
    }
    free(strings);
    return 0;
}

【讨论】:

  • 太好了,谢谢!我还添加了一个 if 语句,当输入为“退出”时,它将中断 while 循环,然后执行用于打印数组的 for 循环。
  • 不客气 ;) 您可以在 unix 上使用 CTRL + D 或在 Windows 平台上使用 CTRL + Z 退出循环,但是,检查“退出”是一个很好的补充。
猜你喜欢
  • 1970-01-01
  • 2017-09-12
  • 1970-01-01
  • 2021-12-30
  • 2015-03-09
  • 1970-01-01
  • 2014-04-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多