函数内部的C++指针创建和赋值
C++ pointer creation and assignment inside the function
*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;
时,内存是在堆上分配的。它不会自动解除分配。所以即使在函数返回之后,内存仍然存在。
相关文章:
- 创建一个类并在C++中使用构造函数(赋值)
- C++的新增功能:创建 2D 数组并具有正确的赋值运算符:分割错误
- 为什么C++编译器会创建复制构造函数和复制赋值运算符
- 创建一个可以通过赋值初始化但不可复制的类型
- 包含字符串值的结构在使用动态内存分配创建后进行赋值时会导致分段错误
- 赋值运算符创建指针,无法删除
- 从初始化构造函数和赋值运算符创建的对象有什么区别
- C++矢量库,为赋值重新创建,最大大小函数
- 为什么有两个额外的析构函数调用,因为我只创建了两个对象并使用重载赋值运算符和增量运算符
- 为用soap_alloc创建的std::string指针赋值
- 常量变量,由函数赋值,用于c++中创建数组
- 如何创建动态分配的const对象数组,但要为其赋值
- 需要帮助在类中创建对象,并为成员函数赋值
- 在c++中创建一个赋值对象
- 为动态字符串数组创建一个不带=赋值的Copy函数
- 为具有引用成员变量的类创建赋值操作符
- 创建了自己的字符串类——重载赋值操作符和析构函数的错误
- 给定了一个变量,编译器是否总能安全地创建赋值操作符?
- 在C++中为类创建赋值(=)运算符
- 为什么在初始化列表中不需要创建额外的副本就可以对数据进行赋值