How to initialize a 3D contiguous array in C -
i know how potentioal non-contiguous array in following way:
int main () { int ***array = (int***)malloc(3*sizeof(int**)); int i, j; (i = 0; < 3; i++) { // assign array[i], not *array[i] (that dereference uninitialized pointer) array[i] = (int**)malloc(3*sizeof(int*)); (j = 0; j < 3; j++) { array[i][j] = (int*)malloc(3*sizeof(int)); } } array[1][2][1] = 10; return 0; } with code above, array[0][j] blocks can not contiguous. contiguous, feel need malloc in way
int* array = (int*)malloc(3*3*3*sizeof(int)); int** y = (int**)malloc(3*3*sizeof(int**)); int*** x = (int***)malloc(3*sizeof(int***)); for(i = 0; < 3; i++) { vals = vals + i*m*n; x[i] = &vals; for(j = 0; j < 3; j++) { x[i][j] = vals + j * n; } } however, got troulbe address assignment. not c programmer, can correct fault? in advance...
int*** x = (int***)malloc(3*sizeof(int***)); should be
int*** x = (int***)malloc(3*sizeof(int**)); now initialization can :
for(i = 0; < 3; i++) { x[i] = y + 3*i; for(j = 0; j < 3; j++) { x[i][j] = array + i*3*3 + j*3; } } so x[0] points first element of y, x[1] fourth, etc. , x[0][0]=y[0] first of array, x[0][1]=y[1] fourth of array, etc.
Comments
Post a Comment