3 ms·
> In C, if you have a declaration `int x[2][3];`, the expression `x[0][4]` is a legal way to access one of the elements Is it really? Does the C-compiler guara
by KeplerBoy 3y ago
> In C, if you have a declaration `int x[2][3];`, the expression `x[0][4]` is a legal way to access one of the elements
Is it really? Does the C-compiler guarantee that your 6 ints will be stored in a contiguous memory area?
- jcranmer 3y agoYes. A[i] in C is exactly equivalent to *(A + i). (Incidentally, this means that 2[x] is a legal expression in C).
- KeplerBoy 3y agoOf course, that part is clear. The question is, if the two rows are guaranteed to be contiguous in memory. If using heap allocated memory, one could easily construct a counterexample (i'm not sure how the stack allocated array behaves, i guess it works because it's the sane choice, but not strictly guaranteed): int *x; int numRows = 2; int numCols = 3; x = (int *)malloc(numRows * sizeof(int )); for (int i = 0; i < numRows; i++) { x[i] = (int )malloc(numCols * sizeof(int)); } // This could segfault x[0][4] = 42;
- jcranmer 3y agoYes, it's a multidimensional array, everything is required to be consecutively allocated. (See 6.5.2.1 for more details). `int[2][3]` is 6 integer objects consecutively allocated (as 3 arrays of 2 arrays of integers), not 3 pointers to arrays of 2 integers.
- KeplerBoy 3y agoThanks for pointing to the actual section. Good to know.
- Someone 3y ago> (Incidentally, this means that 2[x] is a legal expression in C) Even weirder, for that declaration int x[2][3]; I think the following are legal expressions: 0[1[x]] 1[x][0] Or is there something in the language that makes that break parsing?