p = (int *)malloc(m * n * sizeof(int));
If I use p as a two-dimensional dynamic array, how do I access the elements inside?
If you can rely on your C implementation to support variable-length arrays (an optional feature), then a pretty good way would be to declare p as a pointer to (variable-length) array instead of a pointer to int:
int (*p)[n] = malloc(m * sizeof(*p)); // m rows, n columns
Then you access elements using ordinary double indexes, just as if you had declared an ordinary 2D array:
p[0][0] = 1;
p[m-1][n-1] = 42;
int q = p[2][1];
Most widely used C implementations do support VLAs, but Microsoft's is a notable exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With