如何动态分配内存空间为一个字符串,并得到用户的字符串? [英] How to dynamically allocate memory space for a string and get that string from user?

查看:594
本文介绍了如何动态分配内存空间为一个字符串,并得到用户的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用C程序从用户读取输入。我不想使用数组一样,

I want to read input from user using C program. I don't want to use array like,

char names[50];

,因为如果用户给出长度10的字符串,那么剩下的空间被浪费了。

because if the user gives string of length 10, then the remaining spaces are wasted.

如果我用字符指针一样,

If I use character pointer like,

char *names;

然后我需要在这样的方式为分配内存,

then I need to allocate memory for that in such a way of,

names = (char *)malloc(20 * sizeof(char));

在此情况下,也有存储器的浪费的可能性。

In this case also, there is a possibility of memory wastage.

所以,我需要的是动态分配内存的字符串这是完全相同的字符串的长度。

So, what I need is to dynamically allocate memory for a string which is of exactly same as the length of the string.

让我们假设,

如果用户输入计算器,然后分配应 14 (即长度的记忆字符串= 13和1额外空间'\\ 0')

If the user input is "stackoverflow", then the memory allocated should be of 14 (i.e. Length of the string = 13 and 1 additional space for '\0').

我怎么能做到这一点?

推荐答案

一次读取一个字符(使用 GETC(标准输入))和成长串(的realloc ),当您去。

Read one character at a time (using getc(stdin)) and grow the string (realloc) as you go.

下面是我写了前一段时间的函数。注意它只能用于文本输入。

Here's a function I wrote some time ago. Note it's intended only for text input.

char *getln()
{
    char *line = NULL, *tmp = NULL;
    size_t size = 0, index = 0;
    int ch = EOF;

    while (ch) {
        ch = getc(stdin);

        /* Check if we need to stop. */
        if (ch == EOF || ch == '\n')
            ch = 0;

        /* Check if we need to expand. */
        if (size <= index) {
            size += CHUNK;
            tmp = realloc(line, size);
            if (!tmp) {
                free(line);
                line = NULL;
                break;
            }
            line = tmp;
        }

        /* Actually store the thing. */
        line[index++] = ch;
    }

    return line;
}

这篇关于如何动态分配内存空间为一个字符串,并得到用户的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆