函数,字符串作为C中的返回类型

Har*_*nan 2 c function return-type

我需要一个函数来返回一个字符串.我使用以下代码来声明函数:

const char* serv_con(char app_data[50])
{
    char send_data[1024],recv_data[1024];
    //i am avoiding code segments irrelevant to the issue.
    return recv_data;
}
Run Code Online (Sandbox Code Playgroud)

然后像这样调用main中的函数:

int main()
{
    char ser_data[50], app_data[50];
    ser_data[0] = '\0';
    app_data[0] = '\0';
    //avoiding code segments irrelevant to the issue.
    app_data = serv_con(ser_data); //function call
}
Run Code Online (Sandbox Code Playgroud)

编译时会出错:

connect.c:109: error: incompatible types when assigning to type ‘char[50]’ from type ‘const char *’
Run Code Online (Sandbox Code Playgroud)

然后我用std :: string 替换了声明中的const char.声明现在如下:

std::string serv_con(char app_data[50])
{
    char send_data[1024],recv_data[1024];
    //avoiding code segments irrelevant to the issue.
    return recv_data;
}
Run Code Online (Sandbox Code Playgroud)

并以与上述相同的方式调用它.但是它仍然在编译时出现以下错误:

connect.c:13: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘:’ token
Run Code Online (Sandbox Code Playgroud)

请告诉我如何从函数中将字符串作为返回类型.我工作的平台是linux.提前致谢.

dwa*_*ter 9

const char* serv_con(char app_data[50])
{
  char send_data[1024],recv_data[1024];
  //i am avoiding code segments irrelevant to the issue.
  return recv_data;
}
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为您返回一个指向局部变量的指针,该指针在返回后无效.您需要recv_data在堆上进行分配才能在返回后使用它

char* serv_con(char app_data[50])
{
  char send_data[1024];
  char *recv_data = malloc(1024);
  if (!recv_data)
      return NULL;

  // ...
  return recv_data;
 }
Run Code Online (Sandbox Code Playgroud)

然后将主要功能更改为类似的功能

int main()
{
 char ser_data[50];
 char *app_data;
 ser_data[0] = '\0';
 //avoiding code segments irrelevant to the issue.
 app_data = serv_con(ser_data); //function call
 if (!app_data) {
   // error
 }
}
Run Code Online (Sandbox Code Playgroud)