简体   繁体   English

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

[英]Function with string as return type in C

I needed a function to return a string. 我需要一个函数来返回一个字符串。 I used the following code to declare the function: 我使用以下代码来声明函数:

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

and then called the function in the main like this: 然后像这样调用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
}

On compiling it gives the error: 编译时会出错:

connect.c:109: error: incompatible types when assigning to type ‘char[50]’ from type ‘const char *’

Then i replaced the const char in the declaration with std::string. 然后我用std :: string替换了声明中的const char The declaration now is as follows: 声明现在如下:

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

And called it in the same way as mentioned above. 并以与上述相同的方式调用它。 But still it gives the following error on compiling: 但是它仍然在编译时出现以下错误:

connect.c:13: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘:’ token

Please tell me how I can give a string as a return type from a function. 请告诉我如何从函数中将字符串作为返回类型。 The platform I work on is linux. 我工作的平台是linux。 Thanks in advance. 提前致谢。

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

this cannot work, since you're returning a pointer to a local variable, which is invalid after returning. 这不起作用,因为您返回一个指向局部变量的指针,该指针在返回后无效。 You need to allocate recv_data on the heap in order to use it after returning 您需要在堆上分配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;
 }

then change the main function to be something like 然后将主要功能更改为类似的功能

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

What you are doing is a really bad idea. 你在做什么是一个非常糟糕的主意。 The serv_con function allocates some space on the stack for the recv_data array and then returns a pointer to that location. serv_con函数在堆栈上为recv_data数组分配一些空间,然后返回指向该位置的指针。 Of course, as soon as you call another function that data will be wiped out, leading to a bug that is difficult to diagnose. 当然,只要你调用另一个函数就会消除数据,导致一个难以诊断的错误。 If you must return a block of memory from a function, allocate it using malloc . 如果必须从函数返回一块内存,请使用malloc分配。 Basically, never return pointers to objects on the stack. 基本上,永远不会返回指向堆栈上对象的指针。

When you get the pointer out of serv_con you assign it to app_data , which already has some space allocated. 当你从serv_con获取指针时,你将它分配给app_data ,它已经分配了一些空间。 There is no reason for doing this: simply declare app_data as a char * that will point to the storage allocated in serv_con . 没有理由这样做:只需将app_data声明为char * ,它将指向serv_con分配的存储serv_con

Returning pointer to local array or the array itself is a bad idea. 返回指向本地数组或数组本身的指针是一个坏主意。

Even if you do malloc inside the function, the caller needs to free that memory too which is again not a very good practice. 即使你在函数内部执行malloc,调用者也需要释放内存,这也不是一个很好的做法。

I suggest the best way is to pass an out parameter ie pass the array in which you want the result to be copied as a parameter. 我建议最好的方法是传递一个out参数,即传递你希望将结果复制为参数的数组。

int serv_con(char app_data[50], char recv_data[50])
{
    char send_data[1024];
     //recv_data[1024];
    //i am avoiding code segments irrelevant to the issue.
    return 1; // return status success or failure which can be tested in main
}

and then called the function in the main like this: 然后像这样调用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.

    serv_con(ser_data, app_data); //function call
}

I found and corrected a slight mistake. 我发现并纠正了一个小错误。 The app_data you are passing in main is of size 50 where as the one you were trying to return from the function serv_con was 1024. This should be consistent. 您在main中传递的app_data大小为50,而您尝试从函数serv_con返回的app_data为1024.这应该是一致的。 I have used both of size 50 in code above. 我在上面的代码中使用了大小为50的两个。

From your question I can be pretty sure that you are a beginner. 从你的问题我可以很确定你是一个初学者。 Please go through a good text book ie The C Programming Language . 请阅读一本好的教科书,即C语言程序设计

Along with the error you must be getting this. 除了错误,你必须得到这个。
warning: function returns address of local variable. warning:函数返回局部变量的地址。

Look at the warnings always. 始终看警告。 The question is already answered by Greg . 格雷格已经回答了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM