Home > Back-end >  how to correctly use a dynamically allocated array as a (bi)(nth)dimentional one?
how to correctly use a dynamically allocated array as a (bi)(nth)dimentional one?

Time:06-20

If I allocate memory with malloc I get a contiguous chunk of memory:

typedef struct s_point
{
    float   x;
    float   y;
    float   z;
    float   w;
}   t_point;

t_point *matrix = malloc(sizeof(t_point) * (i * j));

But then how can I do something like:

matrix[x][y] = data;

On it? If it it is just a pointer and not a pointer pointer?

CodePudding user response:

You can use a pointer to Variable Length Array:

t_point (*matrix)[n] = malloc(sizeof(t_point[m][n]));

It allocates a contiguous chunk of memory where individual elements are accessible via matrix[i][j]. Just remember to call free(matrix) when the memory is no longer needed.

CodePudding user response:

If you allocated a one dimensional array that simulates a two-dimensional array like

t_point *matrix = malloc(sizeof(t_point) * (m * n));

where m is the number of rows and n is the number of columns. Then for two indices i and j you can write for example

for ( size_t i = 0; i < m; i   )
{
    for ( size_t j = 0; j < n; j   )
    {
        matrix[i * n   j] = data;
    }
}

Actually it is the same if to write

for ( size_t i = 0; i < m * n; i   )
{
    matrix[i] = data;
} 

In the both cases the variable data must have the type t_point. Otherwise you need to assign each data member of objects separately as for example

for ( size_t i = 0; i < m * n; i   )
{
    matrix[i].x = x;
    matrix[i].y = y;
    matrix[i].z = z;
    matrix[i].w = w;
} 

CodePudding user response:

Vlad's and tstanisl's answers are great.

Another way, that support matrix[x][y] syntax, doesn't use VLA and allocate just two continous chunks of memory:

t_point* buf = malloc(sizeof(t_point) * rows * cols);
t_point** matrix = malloc(sizeof(t_point*) * rows);
for(unsigned i = 0; i<rows;   i) {
    matrix[i] = buf   (i*cols);
}
// ...
free(buf);
free(matrix);

It also allows you to do tricks like swapping rows by just reassigning pointers (I don't know if that happens with matrices, but it is sometimes handy with something like argv). If you don't need that, I would probably go for Vlad's method

  • Related