4 ms·
Arrays by row? Why?
by mbq 13y ago
Arrays by row? Why?
- vanderZwan 13y agoBecause normal C is also row-major?
- mbq 13y agoC only has vectors (1D arrays), the implementation of higher dimensions is up to programmer. I know there is this idea to use vectors of vectors to emulate matrices but it is not at all a part of the language (nor efficient).
- beagle3 13y agoSo what do you call x in the definition int x[100][83]; Sure looks like a 2D array of ints for all intents and purposes.
- hello_hi 13y agoThat's not a 2D array, it's a jagged array. You're paying for an extra pointer dereference.
- Peaker 13y agoYou're wrong. Operationally, it is equivalent to: int x_1d[8300]; Where x[a][b] is x_1d[a + 83*b]; An array of arrays is contiguous in memory. There are no pointers involved until you take the (r)value of the array or one of the inner arrays, at which point it is degraded to be a pointer to the array's first element, as always.
- norswap 13y agoAnd I'll also add that this is not an optimization, it's guaranteed by the standard.
- mpweiher 13y agoWhere hello_hi might have gotten confused is that in usage, a pointer of array pointers looks the same as a 2D array. So if you only see x[a][b] it could actually be dereferencing an array of pointers to integers. Since we have the declaration, it's unambiguously the 2D array that you described. EDIT: I might be seeing things, but I think you have your order mixed up, x[a][b] is not x_1d[a + 83b], but rather x_1d[a83+b]
- Peaker 13y agoYour edit is correct, thanks for the correction!
- StefanKarpinski 13y agoEveryone always trots this out when talking about multidimensional array programming in C, but it's effectively useless because it only works for statically declared, fixed-size arrays. Since those never occur when writing real numerical code, the fact that the compiler in this one very particular case can turn x[i][j] into x[i*s+j] for me is essentially useless for any real work with dynamically allocated, variably sized multidimensional arrays.
- mikeash 13y agoIn which case the correct statement would have been something like "Multidimensional arrays in C are not very useful in practice," rather than "they don't exist".
- mbq 13y agoVector of vectors, as I wrote; quoting cdecl "declare x as array 100 of array 83 of int".
- vanderZwan 13y agoWhether it's row-major or "row-major" is not the point, what matters that it is the ordering C programmers will be most familiar with.