在函数中传递的指针的内存位置将被删除

Memory location for a pointer passed in a function gets deleted

本文关键字:位置 删除 内存 指针 函数      更新时间:2023-10-16

问题:我似乎无法将指针设置为在函数内部创建的地址。它总是被设置为Null,我该如何解决这个问题?

问题:我认为问题是由另一个函数内部创建的变量引起的。发生的情况是,在函数执行后,指针再次设置为NULL。



代码:

void listAdd(int *list, int &length) {
    int* tempList = new int[ length + 1 ];
    for( int i = 0; i < length; i ++ )
    {
        (tempList)[ i ] = (list)[ i ];
    }
    cout << " Previous adress: " << hex << list << endl;
    if ( list != NULL )
        delete[] list;
    list = new int[ length + 1 ];
    cout << " New address: " << hex << list << endl << dec;
    for( int i = 0; i < length; i ++ )
    {
        (list)[ i ] = (tempList)[ i ];
    }
    delete[] tempList;
    cout << " Enter a number: ";
    int stored = 0;
    cin >> stored;
    (list)[length -1] = stored;
    length ++;
    cout << " Length: " << length << "n";

    cout << " value at array point 0: "  << (list)[length -1];
    cout << "n retry " << (list)[length-1] <<"n";
    cout << "n n n This is pointing to 0x" << hex << list << 'n' << flush;
}

您似乎希望对list的更改在函数返回后有效:由于list是通过值传递的,因此函数内部操作的对象恰好是您传递的对象的副本。您可能希望通过引用传递对象,即:

void listAdd(int*& list, int &length) {
    // ...
}

或返回结果

int* listAdd(int* list, int& length) {
    // ...
    return list;
}
list = listAdd(list, length);

实际上,您确实希望将对象封装在一个类中,或者只使用std::vector<int>