如何为字符串动态分配内存空间并从用户那里获取该字符串? [英] How to dynamically allocate memory space for a string and get that string from user?
问题描述
我想使用 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.
如果我使用字符指针,
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.
让我们假设,
如果用户输入是"stackoverflow"
,那么分配的内存应该是14
(即字符串的长度=13和1个额外的空间用于' ').
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 ' ').
我怎样才能做到这一点?
How could I achieve this?
推荐答案
一次读取一个字符(使用getc(stdin)
)并增长字符串(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 == '
')
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屋!