从函数返回一个字符串

时间:2014-10-19 18:33:58

标签: c string return

为什么输出错误

输出: 输入您的姓名: saurav 你的名字是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;
}

4 个答案:

答案 0 :(得分:2)

您无法返回指向局部变量的指针。好吧,你可以,但它不会按预期工作。

你的函数应该将指针作为参数并写入:

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);
}

答案 1 :(得分:1)

您可以通过代码中的行更改获得所需的输出。

    #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);
       printf("%s", L);            //changed line
    }

答案 2 :(得分:0)

使用字符串而不是char *:

#include <stdio.h>
#include <conio.h>
#include <iostream> 
#include <string>
using namespace std;

string func();
int main()
{
    cout << "Your name is\n" << func();
    system("pause");
    return 0;
}

string func()
{
    string L;
    printf("Enter ur name:\n");
    cin >> L;
    return L;
}

答案 3 :(得分:0)

使用:

static char L[10];

要保持它,func将不会重入

相关问题