Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two-dimensional dynamic array pointer access

p = (int *)malloc(m * n * sizeof(int));

If I use p as a two-dimensional dynamic array, how do I access the elements inside?

like image 202
chess Avatar asked Jan 23 '26 21:01

chess


1 Answers

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.

like image 115
John Bollinger Avatar answered Jan 25 '26 15:01

John Bollinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!