【问题标题】:C++ pointer creation and assignment inside the function [duplicate]函数内部的C ++指针创建和赋值[重复]
【发布时间】:2015-05-19 06:38:59
【问题描述】:

考虑到这两个例子都发生在函数内部,*p_address= new int(2) 和通过 & p_address = &value 的赋值有什么区别? 例如: 我有 int 指针 *original_pointer。我将它的地址传递给函数。在函数内部,我创建了一个指向 int 值 2 的 int 指针。然后我将指针(在函数内部创建)分配给 *original_pointer。当我在函数外部cout *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;
}

【问题讨论】:

    标签: c++ pointers variable-assignment new-operator


    【解决方案1】:

    *p_address= new int(2) 2 个 int 一个 int(值为 2)分配内存,直到您将其删除为止。

    p_address = &amp;value 只是将 p_address 设置为一个局部变量的地址,该变量在函数退出后立即变为无效(如您所见)。

    【讨论】:

    • new int(2) 不分配 2 个整数。 new int[2] 可以。
    • @BenjyKessler D'oh。你是对的。将编辑更正。
    【解决方案2】:

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

    【讨论】:

    • *p_address= new int(2) 实际上是堆内存上的一个动态内存分配整数。该程序在堆上创建内存。这基本上意味着地址将一直有效到 1。delete[] 运算符由 program.2 显式使用。进程执行停止。发生这种情况时,操作系统会将内存重新分配给其他进程。大多数现代操作系统都这样做。 p_address = &value 基本上是将变量的地址分配给指针。这被分配在堆栈上。这意味着变量只有在范围内才有效。
    【解决方案3】:

    当您使用int value = 2; 时,它会在堆栈上创建。一旦函数返回,变量就会自动释放。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-02
      • 2014-09-06
      • 2021-01-13
      • 2023-04-11
      • 2017-10-12
      • 1970-01-01
      • 2013-01-23
      • 1970-01-01
      相关资源
      最近更新 更多