I don't truly understand some basic things in C like dynamically allocating array of arrays. I know you can do:
int **m;
in order to declare a 2 dimensional array (which subsequently would be allocated using some *alloc function). Also it can be "easily" accessed by doing *(*(m + line) + column)
. But how should I assign a value to an element from that array? Using gcc the following statement m[line][column] = 12;
fails with a segmentation fault.
Any article/docs will be appreciated. :-)
The
m[line][column] = 12
syntax is ok (providedline
andcolumn
are in range).However, you didn't write the code you use to allocate it, so it's hard to get whether it is wrong or right. It should be something along the lines of
Some side-notes:
Using
malloc(3)
for allocate the first array and putting in there pointers created bymalloc(3)
should work witharray[r][c]
because it should be equivalent to*(*(array + r) + c)
, it is in the C standard.Your syntax m[line][colummn] is correct. But in order to use a 2D array in C, you must allocate memory for it. For instance this code will allocated memory for a table of given line and column.
Note, I left out the error checks for malloc for brevity. A real solution should include them.
Here's a modified version of quinmars' solution which only allocates a single block of memory and can be used with generic values by courtesy of
void *
:I'm not sure if it's really safe to cast
void **
toint **
(I think the standard allows for conversions to take place when converting to/fromvoid *
?), but it works in gcc. To be on the safe side, you should replace every occurence ofvoid *
withint *
...The following macros implement a type-safe version of the previous algorithm:
Use them like this:
Humm. How about old fashion smoke and mirrors as an option?
It's not a 2d array - it's an array of arrays - thus it needs the multiple allocations.