How does C allocate space for a 2D (3D...) array when using malloc? -


i having problem understanding how c allocates space 2d (or more dimensional) array, when use malloc , like. take program in this question example.

a one-dimensional array of pointers first defined, pointers arrays of 1d data (in case strings) put in each 1 of boxes of first 1d array. there no guarantee whole 2d array contiguous (the last cell of previous row followed first cell of next row). each 1d array of data can distant, pointers contiguous. correct or missing something? appreciate if me clarify this.

there various ways of doing it, depending on how you're going access it. can ensure main body of array contiguous, or can avoid that. arrays of strings, don't bother making body of array contiguous. 2d (etc) arrays of integers or doubles, make body of array contiguous.

in examples, data type of array generic type t, assumed numeric array elements can assigned 0. examples not error check memory allocations; should in production code.

array access computed indexes — contiguous array body

int n1 = 5; int n2 = 6;  t *a = malloc(n1 * n2 * sizeof(t));  (int = 0; < n1; i++)     (int j = 0; j < n2; j++)         a[i * n2 + j] = 0;  free(a); 

array access double subscripts — contiguous array body

int n1 = 5; int n2 = 6;  t **a = malloc(n1 * sizeof(t*)); t  *b = malloc(n1 * n2 * sizeof(t));  (int = 0; < n1; i++)     a[i] = &b[i * n2];  (int = 0; < n1; i++)     (int j = 0; j < n2; j++)         a[i][j] = 0;  free(b); free(a); 

array access double subscripts — discontiguous array body

int n1 = 5; int n2 = 6;  t **a = malloc(n1 * sizeof(t*));  (int = 0; < n1; i++)     a[i] = malloc(n2 * sizeof(t));  (int = 0; < n1; i++)     (int j = 0; j < n2; j++)         a[i][j] = 0;  (int = 0; < n1; i++)     free(a[i]); free(a); 

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -