3

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?

Roy Ancri
  • 119
  • 2
  • 14

1 Answers1

7

[] has higher precedence than *.

*p[0] = 1; 

should be

(*p)[0] = 1; 

Do the same with others *p occurences.

rafix07
  • 20,001
  • 3
  • 20
  • 33