为什么我得到错误的输出
输出: 输入你的名字: 绍拉夫 你的名字是sa-(
#include <stdio.h>
#include <conio.h>
char * func();
int main()
{
printf("Your name is %s\n",func());
return 0;
}
char* func()
{
char L[10];
printf("Enter ur name:\n");
gets(L);
return L;
}
最佳答案
您不能返回指向局部变量的指针。好吧,你可以,但它不会按预期工作。
你的函数应该获取指针作为参数并在那里写入:
void func(char *L)
{
printf("Enter your name:\n");
gets(L);
}
int main()
{
char L[10];
func(L);
printf("Your name is %s\n", L);
}
请注意,gets()
正是以这种方式定义的。
现在,这段代码是一场灾难。事实上,永远不应该使用 gets(),因为它不会也不可能检查缓冲区溢出。改为:
void func(char *buf, size_t len)
{
printf("Enter your name:\n");
fgets(buf, len, stdin);
}
int main()
{
char L[10];
func(L, sizeof(L));
printf("Your name is %s\n", L);
}
关于c - 从函数返回一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26453978/