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

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

<分区>

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

最佳答案

*p_address= new int(2) 2 ints 一个int(值为2)分配内存,它“一直存在”直到你删除它。

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

关于函数内部的 C++ 指针创建和赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30318393/

相关文章:

vb6 - Visual Basic 6 一条语句中的多个变量赋值

c++ - libcurl C++ 在 POSTing JSON 时出现段错误

c++ - 为什么 C++ 有数组类型?

c++ - 指针和引用 + 重载运算符

c# - 为什么将基类分配给派生类需要显式转换?但不需要做相反的事情

python - 根据其相对于列表中其他值的值在列表中分配变量

C++ 继承和函数覆盖

c++ - 构建调试输出字符串

c++ - 无法打开文本文件,尽管它在我的资源文件中

C# byte* 到 VB.NET BitmapData 扫描线