我需要从用户那里获取未知数量的字符串(通过键盘)并设置一个字符串指针数组,以便它将指向所有输入的字符串。
我定义了一个变量char tmp_strng[]
使用以下代码保存用户输入的字符串:
printf("Enter string number %d\n",num_of_strngs+1);
fflush(stdin);
scanf("%s",tmp_strng);
之后我想分配更多内存给 char *str_arr[]
这是保存指向所有字符串的指针的数组。首先,我通过检查进行内存分配:
if((tmp_str_arr[num_of_strngs]=realloc(str_arr,strlen(tmp_strng)))==NULL)
{
free(str_arr);
printf("Error: couldn't allocate memory. Exiting.");
return 1;
}
str_arr[num_of_strngs]=tmp_str_arr[num_of_strngs];
str_arr[num_of_strngs++]=tmp_strng;
这并没有真正起作用...任何人都可以告诉我这里出了什么问题(或正确)吗?我想尽可能坚持使用 realloc() 和 scanf() 作为主要函数。
最佳答案
使用getline()
函数,它会自动malloc()
足够的内存来容纳该行。使用方法如下:
char* line = NULL; //Setting this to NULL is important!
size_t bufferSize;
size_t characterCount = getline(&line, &bufferSize, stdin);
if(characterCount == (size_t)-1) {
//error handling
} else {
//do something with this line
free(line);
}
getline()
函数与 asprintf()
一样,都是 POSIX-2008 标准的一部分。
关于c - 如何在C中为用户实时输入的字符串分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22235011/