Dynamic 2D array | Sololearn: Learn to code for FREE!

+4

Dynamic 2D array

Can anyone please explain to me how can I allocate, deallocate and reallocate 2D array in C briefly. And assigning values to array. I'm well aware of dynamic memory allocation but want help to understand dynamic memory for 2D array. I guess it's done something like that. char * arr = malloc(rows * column * sizeof(char));

2 Answers

New Answer

+4

Your assumption is correct. Here is an example of using a dynamic 2D array https://code.sololearn.com/cR4p7b4S4MCl/#c Though it does not use realloc().

+3

The size determination is fine rows * column * sizeof((char)). However, you need a new formula to get the item at an index (row, col). If the size of the array is a 3x3. We can get item at index array[1][2] = [1 * 3 + 2]