【发布时间】: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