Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allocate and declare a 3D of array of structs in C?

How do you allocate and declare a 3D array of structs in C? Do you first allocate the array or declare it? I feel like you have to allocate it first so you can declare it so it is on the heap, but then how do you allocate something that hasn't been made yet? Also, should you allocate it all at once or element by element? Also am i putting the structs into the array correctly? My guess on how to do it would be:

header.h

struct myStruct{
   int a;
   int b;
}; 
typedef struct myStruct myStruct_t;

main.c

#include "header.h"
#include <stdio.h>
#include <stdlib.h>
int main(void){

    int length=2;
    int height=3;
    int width =4;
    myStruct_t *elements;
    struct myStruct arr = (*myStruct_t) calloc(length*height*width, sizeof(myStruct);
    //zero based array
    arr[length-1][height-1][width-1];

    int x=0;
    while(x<length){
        int y=0;
        while(y<height){
            int z=0;
            while(z<depth){
                arr[x][y][z].a=rand();
                arr[x][y][z].b=rand();
                z++;
            }
            y++;
        }
        x++;
    }
    return 0;
}    
like image 557
dsb Avatar asked Feb 22 '15 02:02

dsb


People also ask

Can you make a 3D array in C?

Similarly, you can declare a three-dimensional (3d) array. For example, float y[2][4][3]; Here, the array y can hold 24 elements.

How do you declare a 3D array dynamically?

Syntax of a 3D array:data_type array_name[x][y][z]; data_type: Type of data to be stored. Valid C/C++ data type. For more details on multidimensional and, 3D arrays, please refer to the Multidimensional Arrays in C++ article.

How do you enter a 3 dimensional array?

Inserting values in 3D array: In 3D array, if a user want to enter the values then three for loops are used. First for loop represents the blocks of a 3D array. Second for loop represents the number of rows. Third for loop represents the number of columns.


1 Answers

The easy way is:

 myStruct_t (*arr2)[height][width] = calloc( length * sizeof *arr );

Then your loop can access arr2[x][y][z].a = rand(); and so on. If you're not familiar with this way of calling calloc, see here. As usual with malloc, check arr2 against NULL before proceeding.

The triple-pointer approach is not really a practical solution. If your compiler does not support variably-modified types then the array should be flattened to 1-D.

like image 87
M.M Avatar answered Oct 03 '22 09:10

M.M