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:
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. 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. Thanks in advance.
this cannot work, since you’re returning a pointer to a local variable, which is invalid after returning. You need to allocate
recv_dataon the heap in order to use it after returningthen change the main function to be something like