John
John

Reputation: 804

how to create three dimension dynamic array where one of the dimensions is known at compile time in c

How do i create a three dimensional array where only one of the dimensions is known at compile time. The content of the array is struct values as

struct mat
{
char x[3];
int a;
}

struct samp
 {
   int a;
   struct mat;
 }

The array is supposed to store 'samp' and its size is as

   struct samp samp_arr[unknown][10][unknown];

the first time the program runs the first dimension of samp_arr will be one and the last dimension will grow with the number of samp structures put into the array. After a while the first dimension should be incremented by one and any undefined number of samp structs will be put into it. And so on

Upvotes: 0

Views: 427

Answers (2)

Jens Gustedt
Jens Gustedt

Reputation: 78903

If you have a C99 complying compiler you don't have to re-invent the wheel, multi-dimensional arrays even with dynamic bounds are part of the language.

struct samp samp_arr[unknown][10][unknown];

(supposing that unknown is an expression that evaluates to the value of your liking.)

Usually it is a bad idea, though, to allocate such a large variable on the stack, so you should use malloc and friends to allocate it:

struct samp (*samp_arr)[10][unknown] = malloc(sizeof(struct samp[unknown][10][unknown]));
...
// use it
samp_arr[i][j][k].a = ...
...
free(samp_arr);

This declares a pointer to a two-dimensional array.

Wenn passing your array to functions you can do similar, you'd just have to watch that the array bounds come first in the argument list, such that they are known when it comes to the array itself:

int fun(size_t r, size_t s, size_t t, struct samp (*A)[s][t]) {
 ...
}

Upvotes: 1

jørgensen
jørgensen

Reputation: 10551

#include <stdlib.h>
struct samp {
        int a;
};
int main(void)
{
    struct samp *(*sa)[10];
    int first_unknown = 2;
    int second_unknown = 4;
    int i,j,k;

    sa = malloc(sizeof(*sa) * first_unknown);
    for (i = 0; i < first_unknown; ++i) {
        for (j = 0; j < 10; ++j) {
            sa[i][j] = malloc(sizeof(*sa[i][j]) * second_unknown);
            for (k = 0; k < second_unknown; ++k)
                sa[i][j][k].a = 12345;
        }
    }
    return 0;
}

Upvotes: 1

Related Questions