C++ 将指针地址传递给函数

c++ pass pointer address to function

本文关键字:函数 址传 地址 指针 C++      更新时间:2023-10-16

我想在将指针地址传递给该函数时更改函数内的数组值。 当我尝试写入数组时,我收到运行时错误:

Exception thrown at 0x002D1D65 in interviews.exe: 0xC0000005: Access 
violation writing location 0xCCCCCCCC.

我知道我可以用不同的方式做到这一点,但这只是为了我的理解。

这是代码:

void func(int **p){
*p = (int*)calloc(3, sizeof(int)); //have to stay like thiis
*p[0] = 1;  //this line work fine but I think I assign the value 1 
//to the address of the pointer
*p[1] = 2;  //crashing here.
*p[2] = 3;  
}
int main() {
int* pm;       //have to stay like thiis
func(&pm);     //have to stay like thiis
int x =  pm[1];
cout << x;
return 0;
}

我也尝试过

**p[0] = 1;
**p[1] = 2;

但它的崩溃也是如此。

我错过了什么?

[]的优先级高于*

*p[0] = 1; 

应该是

(*p)[0] = 1; 

对其他人做同样的事情*p发生。