c++ pass pointer address to function

2

I want to change array values inside a function when pass the pointer address to this function. When I try to write to the array I receive a runtime error:

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

I know I can do it in different way but its only for my understanding.

this is the code:

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;
}

I tried also with

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

but its crash as well.

What am I missing?

c++
dynamic-memory-allocation
calloc
asked on Stack Overflow Sep 6, 2019 by Roy Ancri • edited Sep 6, 2019 by Roy Ancri

1 Answer

6

[] has higher precedence than *.

*p[0] = 1; 

should be

(*p)[0] = 1; 

Do the same with others *p occurences.

answered on Stack Overflow Sep 6, 2019 by rafix07

User contributions licensed under CC BY-SA 3.0