C++ 为什么回报会改变我的价值?
我正在编写一个函数,它应该返回Hello world!,但是它返回Hello Wo。。我在return语句之前添加了一个cout来检查值,它是正确的 我将两个参数(一个和二个)传递到函数中,我的函数将单词和返回组合在一起。我编写了一个循环,将一个字符转换为一个新字符,这样,由于我正在访问它的数组,所以原始传递的值不会受到影响 功能:C++ 为什么回报会改变我的价值?,c++,loops,return,C++,Loops,Return,我正在编写一个函数,它应该返回Hello world!,但是它返回Hello Wo。。我在return语句之前添加了一个cout来检查值,它是正确的 我将两个参数(一个和二个)传递到函数中,我的函数将单词和返回组合在一起。我编写了一个循环,将一个字符转换为一个新字符,这样,由于我正在访问它的数组,所以原始传递的值不会受到影响 功能: char* myStrCat(char inputOne[], char inputTwo[]){ int sizeOne = myStrLen(input
char* myStrCat(char inputOne[], char inputTwo[]){
int sizeOne = myStrLen(inputOne);
int sizeTwo = myStrLen(inputTwo);
char functionTemp[100];
for(int tempReplace = 0; tempReplace < sizeOne; tempReplace++){
functionTemp[tempReplace] = inputOne[tempReplace];
}
for(int i = 0; i < sizeTwo; i++){
functionTemp[i + sizeOne] = inputTwo[i];
}
cout << "check: " << functionTemp << endl;
return functionTemp;
}
char*myStrCat(char-inputOne[],char-inputwo[]{
int sizeOne=myStrLen(inputOne);
int SIZEWO=myStrLen(输入WO);
char函数temp[100];
对于(int-tempReplace=0;tempReplace coutfunctionTemp
是一个局部变量,并且myStrCat()
返回局部变量的地址,读取编译器警告
与其将functionTemp
作为本地静态数组,不如将functionTemp
作为pointer
并使用new
为pointer
动态分配内存,然后返回指针
编辑:
char* myStrCat(char inputOne[], char inputTwo[]){
int sizeOne = strlen(inputOne);
int sizeTwo = strlen(inputTwo);
int bytes = sizeOne + sizeTwo;
char *functionTemp = new char [bytes + 1];/* allocating memory dynamically for functionTemp */
for(int tempReplace = 0; tempReplace < sizeOne; tempReplace++){
functionTemp[tempReplace] = inputOne[tempReplace];
}
for(int i = 0; i < sizeTwo; i++){
functionTemp[i + sizeOne] = inputTwo[i];
}
cout << "check: " << functionTemp << endl;
return functionTemp;
}
functionTemp
是一个局部变量,并且myStrCat()
返回局部变量的地址,读取编译器警告
与其将functionTemp
作为本地静态数组,不如将functionTemp
作为pointer
并使用new
为pointer
动态分配内存,然后返回指针
编辑:
char* myStrCat(char inputOne[], char inputTwo[]){
int sizeOne = strlen(inputOne);
int sizeTwo = strlen(inputTwo);
int bytes = sizeOne + sizeTwo;
char *functionTemp = new char [bytes + 1];/* allocating memory dynamically for functionTemp */
for(int tempReplace = 0; tempReplace < sizeOne; tempReplace++){
functionTemp[tempReplace] = inputOne[tempReplace];
}
for(int i = 0; i < sizeTwo; i++){
functionTemp[i + sizeOne] = inputTwo[i];
}
cout << "check: " << functionTemp << endl;
return functionTemp;
}
@kiner_shah nothing Changed你真的应该使用(并返回)一些@kiner_shah nothing Changed你真的应该使用(并返回)一些对不起,我很困惑。你能给我一个exmaple@Vincent我修改了上面的内容。对不起,我弄糊涂了。你能给我一个exmaple@Vincent我在上面修改了。