我想找出C中函数gets()的返回值,但我不明白它!
我在一些书中读到:如果成功则返回其参数。 NULL 指针指示错误或文件结束条件。
但参数是一个指向 char 数组的指针。正如我所理解的,返回值也是一个字符指针?
例如:
int main(void)
{
char text[20];
char *c = 0;
printf("Please enter a text: ");
gets(text);
printf("Output: %s\n",text);
printf("Return Value: %p\n",c);
return 0;
}
如果我输入“hello world!”我得到了输出
输出: Hello World ! 返回值:00000000
如果我理解正确的话,返回值显示一个空指针,这意味着错误!?
请帮忙!
最佳答案
您忘记将 fgets
的返回值存储到 c
中,因此它会打印初始化时使用的任何内容。
Return Value
On success, the function returnsstr
.
If the end-of-file is encountered while attempting to read a character, the eof indicator is set (feof
). If this happens before any characters could be read, the pointer returned is a null pointer (and the contents of str remain unchanged). If a read error occurs, the error indicator (ferror
) is set and a null pointer is also returned (but the contents pointed bystr
may have changed).
(http://www.cplusplus.com/reference/cstdio/gets/)
修复代码显示它可以工作:
#include <stdio.h>
int main(void)
{
char text[20];
char *c = 0;
printf("Please enter a text: ");
c = gets(text);
printf("Output: %s\n",text);
printf("Return Value: %p\n",c);
return 0;
}
结果:
warning: this program uses gets(), which is unsafe.
Please enter a text: hello
Output: hello
Return Value: 0x7fff66df0a30
输入 ^D
(在我的操作系统上为 EOF;在其他一些系统上为 ^Z
)会显示一些随机字符,因为数组 text
包含未初始化的字符数据,并且您无论如何都要打印它:
warning: this program uses gets(), which is unsafe.
Please enter a text: Output: &???
Return Value: 0x0
然后打印预期的“返回值”0
。
(该警告是由我的编译器 clang 自动插入的。最好注意它;您可以明白为什么当您输入超过 18 个字符时它会发出警告。)
关于有人可以解释一下 C 语言中 gets() 的返回值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53031555/