c++ - How does a pointer to a pointer correspond to a 2D array? -
i know question asked before, don't understand in context:
here's code i'm trying examine, i'll comment it. please let me know i'm wrong
int **a; // declaring pointer pointer = new int*[n]; // assigning pointer newly-allocated // space (on heap) array // of [size n] of pointers integers (i = 0; < n; ++i) // looping 0 n-1 a[i] = new int[n]; // assigning each slot's pointer // new array of size n? (i = 0; < n; ++i) // loop through rows (j = 0; j < n; ++j) // loop through each column current row a[i][j] = 0; // assign value 0
please let me know i'm wrong. don't understand a = new int*[n];
i'm trying figure out using common sense i'm having troubles.
thank you!
your code , comments correct. clear confusion pointers:
- a 2d array array of arrays.
- in order allow arrays have dynamic size (i.e. size
n
not known @ compile time), array of pointers created. each pointer in array points array of ints. - the resulting structure similar array of arrays - it's array of pointers arrays. pointers there because cannot have e.g.
int a[n][n];
@ compile time because size not known.
here's diagram of this:
> [ ] //">" pointer, pointing @ array ([ ]) [ ] [ ] [ ] > [ ^ ^ ^ ] // array array of pointers "^", each of points array
Comments
Post a Comment