【问题标题】:Why does return change my value? [duplicate]为什么 return 会改变我的价值? [复制]
【发布时间】:2018-07-28 16:35:36
【问题描述】:

我正在编写一个应该返回 Hello world! 的函数,但它返回 Hello Wo.. 我在 return 语句之前添加了一个 cout 来检查值,它是正确的。

我将两个参数传递给函数,一和二,我的函数组合了单词并返回。我编写了一个循环来将一个转换为一个新的字符,因此原始传递的值不会受到影响,因为我正在访问它的数组。

功能:

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;
}

【问题讨论】:

  • @kiner_shah 没有任何改变
  • 你真的应该使用(并返回)一些std::string

标签: c++ loops return


【解决方案1】:

functionTemp 是一个局部变量,myStrCat() 返回局部变量的地址,阅读编译器警告

不要将functionTemp 作为本地静态数组,而是将functionTemp 作为pointer 并使用newpointer 动态分配内存并返回指针。

编辑:

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;
    }

在调用函数时,一旦你得到连接的字符串/动态地址,使用delete 释放它以避免内存泄漏。一个简单的调用函数看起来像

int main() {
        char *temp = NULL;
        temp = myStrCat("Stack","overflow");/* temp holds dynamic address */
        cout<<temp<<endl;
        /* free the dynamically allocated memory */
        delete [] temp ;

        return 0;
}

【讨论】:

  • 对不起,我很困惑。你能给我看一个例子吗
  • @Vincent 我在上面修改了。
猜你喜欢
  • 1970-01-01
  • 2020-01-11
  • 2021-01-28
  • 2023-03-09
  • 2019-09-22
  • 2015-11-22
  • 2018-12-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多