我想在将指针地址传递给此函数时更改函数内的数组值。 当我尝试写入数组时收到运行时错误:
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
次事件执行相同的操作。
关于c++将指针地址传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57822921/