Vanos Sege
Vanos Sege

Reputation: 1

C Language, dynamic 3d array

I have to create a dynamic and 3 dimensional integer-Array in C.

But I have to create the pointers separately and use malloc. I know how to create 2d Array with malloc but I get confused using the following method, and i couldn't really find other question similar to this.

2x2x2 Integer-Array

First step:

int *firstD;  
firstD = (int) malloc(2*sizeof(int));

Second step:

int *secondD;  
secondD = (int) malloc(2 * firstD * sizeof(int));

Third step:

int *thirdD;  
thirdD = (int) malloc(2 * secondD * sizeof(int));

I think maybe I have to add pointers in the starting (int*) and increase it every stepp by one more pointer?

Upvotes: 0

Views: 50

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

  1. Allocate an array to store pointers to arrays of row pointers.
  2. Allocate arrays to store row pointers.
  3. Allocate arrays to store each rows.
#include <stdlib.h>

int main(void) {
    int size1 = 2, size2 = 2, size3 = 2;
    int*** array;
    array = malloc(sizeof(int**) * size1); // 1
    for (int i = 0; i < size1; i++) {
        array[i] = malloc(sizeof(int*) * size2); // 2
        for (int j = 0; j < size2; j++) {
            array[i][j] = malloc(sizeof(int) * size3); // 3
        }
    }

    // free arrays
    for (int i = 0; i < size1; i++) {
        for (int j = 0; j < size2; j++) {
            free(array[i][j]);
        }
        free(array[i]);
    }
    free(array);

    return 0;
}

I wrote type names explicitly in the above example, but I suggest using dereferencing to obtain size of elements to allocate is better to prevent causing typos.

#include <stdlib.h>

int main(void) {
    int size1 = 2, size2 = 2, size3 = 2;
    int*** array;

    // allocate arrays
    array = malloc(sizeof(*array) * size1); // 1
    for (int i = 0; i < size1; i++) {
        array[i] = malloc(sizeof(*array[i]) * size2); // 2
        for (int j = 0; j < size2; j++) {
            array[i][j] = malloc(sizeof(*array[i][j]) * size3); // 3
        }
    }

    // free arrays
    for (int i = 0; i < size1; i++) {
        for (int j = 0; j < size2; j++) {
            free(array[i][j]);
        }
        free(array[i]);
    }
    free(array);

    return 0;
}

Onitted in the above examples to make them simple, but you should check results of malloc() to see if the allocations are successful.

Upvotes: 1

Related Questions