scanf动态分配 [英] scanf dynamic allocation
问题描述
无论什么原因,以下代码打印(null):
For whatever reason the following code prints (null):
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *foo;
scanf("%ms", &foo);
printf("%s", foo);
free(foo);
}
我正在动态地为字符串分配内存,但正如我之前所说我的程序只输出(null)。我通过使用getche和realloc做一个函数来解决这个问题,但是似乎几乎没有意义,因为我还必须编程如果用户进入backspace,tab等等会发生什么。但正如我所说的只是一个工作我宁愿知道为什么上面的代码不工作...
I'm trying to allocate memory for a string dynamically but as I said earlier my program simply outputs (null). I worked around this by making a function using getche and realloc but it seems almost pointless due to the fact that I also had to program what would happen if the user entered backspace, tab, etc.. But as I said that is just a work around and I would rather know why the above code is not working...
附加信息:
我我使用Pelles C IDE v7.00并用C11标准编译
I am using the Pelles C IDE v7.00 and compiling with the C11 standard
推荐答案
我没有看到 %m
在草案C11标准( fscanf
的部分)。我建议你避免它,并像C99一样调用 malloc()
。
I am not seeing %m
in section 7.21.6.2 of the Draft C11 standard (the section on fscanf
). I suggest that you avoid it and call malloc()
as you would in C99.
这篇关于scanf动态分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!