1、指针变量的传值与传址
func函数的形参是整形指针类型 int * pRes,要在函数体内改变 pRes的值,并把这个变化返回到main函数中,必须传递pRes的指针。因为pRes本身就是指针,所以应该传递指针的指针,或者指针的引用:
int func(int* &p) {
if (p == nullptr) {
p = new int(12);
}
return 0;
}
int main() {
int* p = nullptr;
int val = func(p);
cout << val << endl;
cout << *p << endl;
return 0;
}
函数中传递指针或引用参数,要注意修改是指针本身还是指针的内容,若不希望改变指针本身,建议加 const声明,如:function_b(int * const num)
上面的例子是改变指针本身(由nullptr转向int *),所以是:
p = addr;
下面的例子是改变指针所指值,所以是:
void func(int* const p) {
int b = 20;
int* buf = &b;
*p= *buf;
}
// *p = *addr;
// 由于没有改变指针本身,所以就不需要加上&
No comments yet.