Select array 6xNxN

I have a variable N. I need an array 6xNxN.

Something like that:

int arr[6][N][N];

But obviously this does not work.

I'm not sure how I would decide to highlight this so that I can access, for example. arr[5][4][4]if Nequal to 5, and arr[5][23][23]if Nequal to 24.

Please note that it Nwill never change, so I will never have to realloceat arr.

What should I do? Will it work int ***arr = malloc(6 * N * N * sizeof(int));?

+3
source share
4 answers

Simply changing the declaration on this line and saving malloccan easily solve your problem.

int ***arr = malloc(6 * N * N * sizeof(int));

int *** ( ). , :

int *flatarr = malloc(6 * N * N * sizeof(int));

, arr[X][Y][Z], , flatarr[(X*N*N) + (Y*N) + Z]. , :

#define arr(X,Y,Z) flatarr[((X)*N*N) + ((Y)*N) + (Z)]

, Cubically, . Code Golf Dennis , .

0

int (*arr)[N][N] = malloc(sizeof(int[6][N][N]));

free(arr);

, @StoryTeller, -

int (*arr)[N][N] = malloc(6u * sizeof(*arr));

u 6, .

, , size_t , int, @chqrlie, " ", .

+3

int arr[6][N][N]; . C 1999 , (VLA) .

( GCC, 5.0, , C, -std=c99 -std=c11.)

, , :

int (*arrptr)[Y][Z] = malloc( sizeof(int[X][Y][Z]) );

int ***arr = malloc(6 * N * N * sizeof(int));, int*** 3D-. , - , .

: .

+2

, , . , , , :

, , . ( , sizeof, _Alignof &), , .

.

int a[42];

a int *, : a[18] => *(a + 18).

( "" "", ), "" - . , :

int a[16][42];

a int ()[42] (42- int). , int *. a? , int ()[42], a 42- int: int (*)[42]. , :

a[3][18] => *(*(a + 3) + 18)

a a int (*)[42], 3 42 * sizeof(int). , .

, n- .


- , .

  • 6*N*N. , N -.

  • , , int ( ). , ,

    int ***a = malloc(6 * sizeof *int);
    for (size_t i = 0; i < 6; ++i)
    {
        a[i] = malloc(N * sizeof *(a[i]));
        for (size_t j = 0; j < N ++j)
        {
            a[i][j] = malloc(N* sizeof *(a[i][j]));
        }
    }
    // add error checking to malloc calls!
    

    , 3D-, , .

    , , . a[2*N*N+5*N+4] 2,5,4, .

+1

Source: https://habr.com/ru/post/1683574/


All Articles