我需要一个函数来返回一个字符串。我用下面的代码声明函数:带字符串作为返回类型的函数C
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;
}
然后叫这样的主要功能:
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
}
在编译它给人的错误:
connect.c:109: error: incompatible types when assigning to type ‘char[50]’ from type ‘const char *’
然后我用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;
}
并以与上述相同的方式调用它。但它仍然提供了有关编译以下错误:
connect.c:13: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘:’ token
请告诉我,我怎么可以给一个字符串从一个函数返回类型。我工作的平台是linux。提前致谢。
这不是C++。不要标记它C++。 –
你为什么使用const?这意味着值不能被修改。而你仍然试图在代码中的某处修改它。 – Milee
我避开了'const',并尝试了'char *',但它仍然给出了相同的错误。 –