2016-04-01 98 views
1

我在使用返回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; 
} 

而在主我爲了訪問給函數有這樣的代碼:

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

其中C1,C2和C3被定義爲:

char *c1,*c2,*c3; 

在功能方面,infotot取權值:

*infotot="c1;c2;c3;" 

但是問題出現在主要信息中,信息取值如下:

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

其中第一個字母「l」對應於c1的第一個字母。我怎麼能解決它,以便有info =「c1; c2; c3;」?

+0

你分配一個'char',而不是一個字符串,這就是爲什麼只有第一個字母出現 – OMGtechy

+0

您將指針傳遞到一個字符指針?你知道格式''%s「'需要一個C風格的*字符串*嗎?即由零終止的字符數組。如果沒有合適的[最小,完整和可驗證示例](http:// stackoverflow。com/help/mcve),但它看起來像*未定義的行爲*給我。 –

+2

'return * infotot;'相當於'return infotot [0];'。 '* info = gatherinfo(c1,c2,c3);'相當於'info [0] = gatherinfo(c1,c2,c3);' – molbdnilo

回答

1

char infotot[256];將被釋放時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); 
} 

爲了改善這一點,你可以使用std::string

+0

謝謝!它工作完美。我想避免使用字符串,因爲以後我會在char模式中需要這些信息,所以爲了避免將來的字符串轉換,這個解決方案是完美的。 – Zarauztarra

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運營商+(串聯)

std::string gatherinfo(char *c1,char *c2,char *c3){ 
    return std::string(c1) + ";" + c2 + ";" + c3 + ";"; 
} 
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 
}