考虑到两个示例都在函数内部发生,*p_address= new int(2)
和& p_address = &value
赋值之间的区别是什么?例如: 我有int指针* original_pointer。我将它的地址传递给函数。在函数内部,我创建了一个int指针,指向2的int值。然后,我将指针(在函数内部创建)分配给* original_pointer。当我在* original_pointer函数外面,它返回-858993460,同时里面的函数返回值为2. 但是,当我用新建在函数里面创建一个指针时,* original_pointer内外功能是一样的。 下面是代码:函数内部的C++指针创建和赋值
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;
}
new int(2)不分配2个整数。新的int [2]没有。 –
@BenjyKessler D'oh。你是对的。将编辑更正。 – John3136