我不能在函数中使用新功能C++构建

I can't use new in C++ function to build

本文关键字:新功能 C++ 构建 不能 函数      更新时间:2023-10-16

我想在此功能中为参数提供新的空间。

void Binary::PreAndMid(Qnode* root, char temp1[], char temp2[], int m, int n, int j, int k) {
    if (n - m != k - j || m > n || j > k) {
        return;
    }
    else {
        root = new Qnode;  /*in other function the root is become null*/
        root->val = temp1[m];
        cout << root->val << endl;
        int f = Find(temp2, temp1[m]);
        if (f == -1) {
            return;
        }
        else {
            PreAndMid(root->LC, temp1, temp2, m + 1, m + f - j, j, f - 1);
            PreAndMid(root->RC, temp1, temp2, m + f - j + 1, n, f + 1, k);
        }
    }
}

结果是根为null。

这是因为您需要进行*& root,以便在末尾返回新的内存地址。现在,您正在违反该规则永远不会在参数上使用分配运算符。

参数 root作为指针的副本传递。从功能返回后,将新值分配给该指针不会延续。

如果您愿意,则需要通过参考来传递指针rootQnode* &root,它将确保呼叫此功能的代码和功能本身使用相同的变量。