08-30-2022, 07:14 PM
(08-30-2022, 06:50 PM)Kernelpanic Wrote: You have a fundamental problem understanding how multidimensional arrays are stored in the computer.
Regardless of whether it is one, two or three-dimensional, it is stored linearly in the computer. But the numerical example shows that the individual values can only be accessed via <row> - column>. The same applies to character strings.
Character strings in C are basically fields of the "char" type. And regarding of a pointer is an unindexed array name a pointer to the first array element:
char x[10];
The following two statements are identical:
x
&x[0]
I think it's worth mentioning that it's easy to get it confused because an array of pointers and a multidimensional array can both be accessed by doing `[a][b]`. But they are fundamentally different as you've noted, multidimensional arrays are one block of memory and the index gets calculated via the size of the array, there is only one memory access going on when you do `[a][b]`. Where-as if you use `[a][b]` on a `char *strs[10]` then `[a]` and `[b]` do separate memory accesses, once in the array of pointers and another in the array of char's.
I also think the difference gets a bit more obvious once you start to see pointers to arrays. An array of string pointers like `char *strs[10]` can be assigned and used as a `char **`, but a `char a[3][9]` cannot be treated as one. Instead, it can be treated as a `char (*x)[9]`, a pointer to an array of 9 chars, with `char a[3][9]` then being thought of as an array of arrays of 9 chars, all together in one thing.