Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C language not support column major array? [closed]

Tags:

c

Is it only a random design choice or is there any specific reason that C supports row-major not column-major? I know that Fortran uses column major. So what is the reason(if any) behind these design choices?

like image 940
Sreeja Das Avatar asked Jan 07 '13 18:01

Sreeja Das


Video Answer


2 Answers

Basing my answer on some of the comments to the question as well as some other answers (and some of my own reflections - but notably no knowledge whatsoever of the C language design process...), I believe this is a choice based on merely what the people making this decision (Ritchie?) needed themselves.

If you interpret the indices of a multidimensional array as matrix indices, it makes sense to have the first index as a row index and the second as a column index - i.e. a column-major structure. If your applications are going to be heavy on linear algebra or other matrix-heavy computations, it also makes sense to store these structures in a way that makes it efficient to traverse them one column at a time, since many algorithms do this. For this reason, programming languages such as Matlab and Fortran benefit from being column-major - it makes it easier to write efficient code with matrices and matrix algorithms in mind.

C, on the other hand, is much more general-purpose than e.g. Matlab or Fortran. If you're not going to use int** specifically for matrices, it doesn't really matter which index is which. And it seems natural that if a is an int**, then a[2] returns an int* and a[2][1] returns an int - you "dig deeper" into the multidimensional array. For efficiency, we now only care that if we pick out a[2] and want to iterate it, it should be cached efficiently. It doesn't matter if you, the programmer, are associating a[2] with a matrix row or a matrix column - we're not working with matrices!

Thus, there is no strong case (that I can make out off the top of my head) for C to be column-major. At the time of implementing the first versions, it might just have been easier to make it row-major - perhaps because the underlying low-level language (assembler?) was already row-major - and that was that.

like image 168
Tomas Aschan Avatar answered Dec 02 '22 17:12

Tomas Aschan


In C array elements are guaranteed to be contiguous memory elements, and a 2 dimensional array is an array of arrays, so say for an array int a[10][20]; a[0] is itself an array, and its elements must be contiguous. Equally a[0] is contiguous with a[1].

like image 37
Clifford Avatar answered Dec 02 '22 18:12

Clifford