
Different ways of implementing a 2d array
If I want a two dimensional array there is essentially two
ways of allcating memory. I would like some comments about
which of the following methods you prefer. I think method
1 is the best way of doing things
Error checking omitted for brevity. The code is only meant to
demonstrate the general ideas and so there are quite a few
things that can be done better.
Method 1:
Allocate memory for an array of pointers, then make each of those
pointers point to allocated memory. Access is done through normal
array indexing.
#include <stdlib.h>
int **alloc2d(size_t cols, size_t rows)
{
int **tmp = malloc(cols * sizeof *tmp);
int i = 0;
for(i = 0;i < cols;i++)
{
tmp[i] = malloc(rows * sizeof *tmp[0]);
}
return tmp;
Quote:
}
Method 2:
Most of this would be wrapped up in struct of course,
but the general idea should be clear. Use a single big
array and calculate the offsets using a macro or
function.
#include <stdlib.h>
size_t rows;
size_t cols;
/*Use this macro to access the array*/
#define ACCESS(arr, x, y) (*((arr) + ((y) * cols) + (x)))
int *alloc2d(size_t col, size_t row)
{
int *tmp = malloc(col * row * sizeof *tmp);
rows = row;
cols = col;
return tmp;
Quote:
}
--
Thomas