Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I correctly set up, access, and free a multidimensional array in C?

Tags:

I have seen dozens of questions about “what’s wrong with my code” regarding multidimensional arrays in C. For some reason people can’t seem to wrap their head around what is happening here, so I decided to answer this question as a reference to others:

How do I correctly set up, access, and free a multidimensional array in C?

If others have helpful advice, please feel free to post along!

like image 480
Mike Avatar asked Sep 17 '12 15:09

Mike


People also ask

How do you access a multi dimensional array?

Accessing multidimensional array elements: There are mainly two ways to access multidimensional array elements in PHP. Elements can be accessed using dimensions as array_name['first dimension']['second dimension']. Elements can be accessed using for loop. Elements can be accessed using for each loop.


2 Answers

In C since C99, even dynamic multidimensional arrays can be easily allocated in one go with malloc and freed with free:

double (*A)[n] = malloc(sizeof(double[n][n]));  for (size_t i = 0; i < n; ++i)   for (size_t j = 0; j < n; ++j)       A[i][j] = someinvolvedfunction(i, j);  free(A); 
like image 93
Jens Gustedt Avatar answered Oct 30 '22 02:10

Jens Gustedt


There are at least four different ways to create or simulate a multi-dimensional array in C89.

One is "allocate each row separately", described by Mike in his answer. It is not a multidimensional array, it merely imitates one (in particular it mimics the syntax for accessing an element). It can be useful in the case where each row has different size, so you aren't representing a matrix but rather something with a "ragged edge".

One is "allocate a multidimensional array". It looks likes this:

int (*rows)[NUM_ROWS][NUM_COLS] = malloc(sizeof *rows); ... free(rows); 

Then the syntax to access element [i,j] is (*rows)[i][j]. In C89, both NUM_COLS and NUM_ROWS must be known at compile-time. This is a true 2-D array, and rows is a pointer to it.

One is, "allocate an array of rows". It looks like this:

int (*rows)[NUM_COLS] = malloc(sizeof(*rows) * NUM_ROWS); ... free(rows); 

Then the syntax to access element [i,j] is rows[i][j]. In C89, NUM_COLS must be known at compile-time. This is a true 2-D array.

One is, "allocate a 1-d array and pretend". It looks like this:

int *matrix = malloc(sizeof(int) * NUM_COLS * NUM_ROWS); ... free(matrix); 

Then the syntax to access element [i,j] is matrix[NUM_COLS * i + j]. This (of course) is not a true 2-D array. In practice it has the same layout as one.

like image 34
Steve Jessop Avatar answered Oct 30 '22 01:10

Steve Jessop