Re:C Strings and my slow descent to madness
by quelsolaar on Friday April 07, 2023 @12:55AM
(#35478168)
Its been 50 years so pretty much everything has been considered. In my opinion the mistake was not having arrays decay in to pointers but rather arrays should be pointers in the first place. An array should be seen as a number of values where with a pointer pointing at the first one. I think adding a third version of the same functionality would just complicate things further. (&p[42] is a "slice" of an array) Another thing I do not like about slices that store lengths, is that they hide memory layout from the user and that is not a very C thing to do.
[ Parent
| on HN ]
If you think about arrays as pointers, you will get a lot of things wrong, e.g.
float m[10][10];
it not a an array of pointers, but a 2D dimensional array with 2D memory layout.
Re:C Strings and my slow descent to madness
by quelsolaar on Friday April 07, 2023 @06:25AM
(#35480103)
You are right, sizeof is the other big difference. I think these differences are small enough that it was a mistake separate the two. The similarities / differences do make them confusing.
How would you express a 2D memory layout with only pointers?
Re:C Strings and my slow descent to madness
by colejohnson66 on Friday April 07, 2023 @11:19AM
(#35482475)
An array of pointers to arrays? Basically, a `T**` C#'s "jagged" arrays are like this, and to get a "true" 2D array, you use different syntax (a comma in the indexer):
int[][] jagged; // an array of `int[]` (i.e. each element is a pointer to a `int[]`)
int[,] multidimensional; // a "true" 2D array laid out in memory sequentially
// allocate the jagged array; each `int[]` will be null until allocated separately
jagged = new int[][10];
Debug.Assert(jagged.All(elem => elem == null));
for (int i = 0; i < 10; i++)
jagged[i] = new double[10]; // allocate the internal arrays
Debug.Assert(jagged[i][j] == 0);
// allocate the multidimensional array; each `int` will be `default` which is 0
// element [i,j] will be at offset `10*i + j`
multiDimensional = new double[10, 10];
Debug.Assert(multiDimensional[i, j] == 0);