函数内部的C++指针创建和赋值

C++ pointer creation and assignment inside the function

本文关键字:创建 赋值 指针 C++ 内部 函数      更新时间:2023-10-16

*p_address= new int(2)和通过&p_address = &value考虑到这两个例子都发生在函数内部?例如:我得到了int指针*original_pointer。我将其地址传递给函数。在函数内部,我创建了一个指向int值2的int指针。然后,我将指针(在函数内部创建(分配给*original_pointer。当Icout函数外的*original_pointer时,它返回-858993460,而在函数内,它返回值2。但是,当我使用new在函数内部创建指针时,函数内部和外部的*original_pointer值是相同的。这是代码:

int main() {
    while (true) {
        void assign_(const int**);
        char* tmp = " ";
        int const *original_pointer;
        assign_(&original_pointer);
        cout << "the address of original_pointer is " << original_pointer << endl;
        cout << "the value of original_pointer is " << *original_pointer << endl;
        cin >> tmp;
    }
    return 0;
}
void assign_( int const **addr) {
    int* p_value;
    int value = 2;
    p_value = &value;
    *addr = p_value;
    //*addr = new RtFloat(2.0);   // If I create the pointer this way the value of *addr is the same with *original_pointer
    cout << "the adress of *addr inside the function is " << *addr << endl;
    cout << "the value of **addr inside the function is " << **addr << endl;
}

*p_address= new int(2)2 int一个int(值为2(分配内存,该int"有效",直到您删除它。

p_address = &value只是将p_address设置为局部变量的地址,一旦函数退出(如您所见(,该地址就会变为无效。

*p_address= new int(2)和通过&p_address = &value;赋值的区别在于,在第一种情况下,p_address指向的值在堆上,而在第二种情况下则在堆栈上。这意味着p_address所指向的值在第一种情况下的生存期是直到它被删除,而在第二种情况下,它只有在值超出范围之前才有效。

使用int value = 2;时,它是在堆栈上创建的。一旦函数返回,变量将自动解除分配。

当您使用*p_address= new int;时,内存是在堆上分配的。它不会自动解除分配。所以即使在函数返回之后,内存仍然存在。