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;
}
Similarly, you can declare a three-dimensional (3d) array. For example, float y[2][4][3]; Here, the array y can hold 24 elements.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With