Ask coding questions

← Back to all posts
Why not Dereference it?
SourabhPrasad (0)

When assigning value in 2D array, we should put ** because we are accessing memory location? Am I right or wrong?

Answered by 19wintersp (1120) [earned 5 cycles]
View Answer
19wintersp (1120)

If you want to assign a value to a pointer in an array, you can just do it like this:

int main() {
  int **p = new int*[2];

  *(p[0]) = 1; //assign value
  p[1] = new int[2]; //assign pointer

Note that when assigning a value, you should point to an accessible memory location first otherwise you will obtain a Segmentation Fault. So, a better version of line 4 would be:

p[0] = new int(1);