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

标签 c++ dynamic-memory-allocation calloc

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

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/

相关文章:

c++ - CUDA 真的没有类似 calloc() 的 API 调用吗?

c - 我在使用 calloc 创建处理矩阵的函数时遇到问题

c++ - 调用 ' ' 没有匹配的函数

c - 访问数组段错误中的数据

c++ - OpenMP 并行化停止工作

c++ - 为什么看起来像将int分配给int *时此分配是正确的?

c - C 中的内存访问冲突 : Trying to write substrings from char** to char**

C:如何指向calloc数组?

c++ - 如果索引表示为 x y 位置,则检查哪些 2d 数组元素彼此更接近

c++ - 将类型序列与 iostream 混合的最简单方法?