从函数返回错误的信息

时间:2016-04-01 11:27:35

标签: c++ function pointers char printf

我在使用返回char的函数时遇到问题。这是函数的代码,它将3个字符(c1,c2,c3)收集到1(infotot)中:

char gatherinfo(char *c1,char *c2,char *c3){
    char infotot[256];
    int n=sprintf(infotot,"%s;%s;%s;",c1,c2,c3);
    return *infotot;
}

在main中我有这段代码才能访问该函数:

char info[256];
    *info=gatherinfo(c1,c2,c3);

其中c1,c2和c3定义为:

char *c1,*c2,*c3;

在该功能中,infotot采用正确的值:

*infotot="c1;c2;c3;"

但问题是主要的,其中info采用以下值;

*info="lÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ"

第一个字母“l”对应于c1的第一个字母。我怎么能解决它才能有info =“c1; c2; c3;”?

3 个答案:

答案 0 :(得分:4)

gatherinfo返回一个字符,而不是字符串。您将该char分配给数组info的第一个元素。

此数组未终止,因此当您打印它时,您会看到第一个元素后跟垃圾。

您必须返回std::string。可以复制std :: string。

std::string gatherinfo(char *c1,char *c2,char *c3){
    char infotot[256];
    sprintf(infotot,"%s;%s;%s;",c1,c2,c3);
    return infotot; // Here infotot is used to construct the std::string returned by the function. Same as return std::string(infotot);
}

您也可以使用std :: string operator +(concatenation)

std::string gatherinfo(char *c1,char *c2,char *c3){
    return std::string(c1) + ";" + c2 + ";" + c3 + ";";
}

答案 1 :(得分:1)

<{1}}返回后,

char infotot[256];将被取消分配。

我会在main中分配目标缓冲区并将其传递给函数:

gatherinfo

要改善这一点,您可以使用char info[256]; gatherinfo(info,c1,c2,c3); void gatherinfo(char *infotot,char *c1,char *c2,char *c3){ sprintf(infotot,"%s;%s;%s;",c1,c2,c3); }

答案 2 :(得分:0)

gatherinfo返回单个字符(不是字符串)。

你将这个单个字符(它将是c1的第一个字符)写入info的第一个字符 - 但是关键的是,之后你不会写一个空字符。

修复是gatherinfo应该返回std::string。 (而且我怀疑它应该把它的参数作为const std::string&)。所以:

std::string gatherinfo(
   const std::string& c1, const std::string& c2, const std::string& c3){
    return c1 + ';' + c2 + ';' + c3
}