3 ms·
Another one corner of the language where arrays actually being arrays is important is multidimensional array access: int arr[5][7]; arr[3][5] = 4; // e
by Joker_vD 4y ago
Another one corner of the language where arrays actually being arrays is important is multidimensional array access:
int arr[5][7];
arr[3][5] = 4; // equivalent to *(*(arr + 3) + 5) = 4;
This works because (arr + 3) has type "pointer to int[7]", not "pointer to int". The resulting address computation is
(char*)arr + 3 * sizeof(int[7]) + 5 * sizeof(int) ==
(char*)arr + 26 * sizeof(int)
That's also another reason why types like "int [5][7][]" are legal but "int [5][][]" are not.
- ErikCorry 4y agoReally, are multidimensional arrays an important part of the language? The above code looks like it's indexing into an array of pointers. If you want a flat array, make a few inlined helper functions that do the multiplying and adding. Your code will be much cleaner and easier to understand.
- Joker_vD 4y agoOf course multidimensional arrays are an important part of the language, just as the ability to have structs inside structs. > The above code looks like it's indexing into an array of pointers. If you want a flat array, make a few inlined helper functions that do the multiplying and adding. Your code will be much cleaner and easier to understand. It is a "flat" array already, not an array of pointers: [0]. No need to write the code that compiler generates for you already. [0] https://godbolt.org/z/x3cPf3TvT https://godbolt.org/z/x3cPf3TvT
- ErikCorry 4y agoI am aware that it's flat already.
- int_19h 4y agoThe code above does not mention any pointer types, so why would you assume that it's indexing into an array of pointers? I can't think of any reason why get(a, i, j) is more readable than a[i][j].