Strcat()在strcpy之后返回垃圾

时间:2015-11-29 15:35:47

标签: c++

为什么这不起作用?用strcat注释它返回第一个char * OK,但是如果strcat取消注释,我会得到垃圾字符。

char * concat(char* first, char* second){
  char result[10];   // array to hold the result.
  strcpy(result,first); // copy string one into the result.
  strcat(result,second); // append string two to the result.
  return result;
}
concat(rPlayer.name,"blbost");

1 个答案:

答案 0 :(得分:1)

您将向函数本地的第一个元素返回一个地址,该函数在函数返回后不再有效(/ exists)。

first应该附加second数组的内容。您需要确保first已经分配了足够的空间来附加second数组中的所有字符,以免遇到未定义的行为。