What's the difference between arrays of arrays and multidimensional arrays? - c

I had a language-agnostic discussion with someone in the C++ chat and he said that arrays of arrays and multidimensional arrays are two things.
But from what I learned, a multidimensional array is nothing more than an array of other arrays that all have the same size. In particular he is saying
Well, they kind of are in C, where you simulate multiple dimensions with nested arrays
but that’s only because C doesn’t actually support multiple dimension arrays
Can someone please explain what the canonical computer-science definition of "multiple dimension arrays" is and why C (or the abstract definition "array of arrays") does not fit that definition?

Take .NET arrays which illustrate this nicely:
C# has a distinction between jagged arrays which are defined in a nested fashion:
int[][] jagged = new int[3][];
Each nested array can have a different length:
jagged[0] = new int[3];
jagged[1] = new int[4];
(And note that one of the nested arrays isn’t initialised at all, i.e. null.)
By contrast, a multidimensional array is defined as follows:
int[,] multidim = new int[3, 4];
Here, it doesn’t make sense to talk of nested arrays, and indeed trying to access multidim[0] would be a compile-time error – you need to access it providing all dimensions, i.e. multidim[0, 1].
Their types are different too, as the declarations above reveal.
Furthermore, their handling is totally different. For instance, you can iterate over the above jagged array with an object of type int[]:
foreach (int[] x in jagged) …
but iterating over a multidimensional array is done with items of type int:
foreach (int x in multidim) …
Conceptually, a jagged array is an array of arrays (… of arrays of arrays … ad infinitum) of T while a multidimensional array is an array of T with a set access pattern (i.e. the index is a tuple).

I would expect multidimensional arrays to offer operations such as "Give me the number of dimensions" or "Give me a certain column" or "Give me a certain sub-view". C arrays don't offer these operations.

From Wikipedia:
Multi-dimensional arrays
The number of indices needed to specify an element is called the dimension, dimensionality, or rank of the array type. (This nomenclature conflicts with the concept of dimension in linear algebra,[5] where it is the number of elements. Thus, an array of numbers with 5 rows and 4 columns, hence 20 elements, is said to have dimension 2 in computing contexts, but represents a matrix with dimension 4-by-5 or 20 in mathematics. Also, the computer science meaning of "rank" is similar to its meaning in tensor algebra but not to the linear algebra concept of rank of a matrix.)
Many languages support only one-dimensional arrays. In those languages, a multi-dimensional array is typically represented by an Iliffe vector, a one-dimensional array of references to arrays of one dimension less. A two-dimensional array, in particular, would be implemented as a vector of pointers to its rows. Thus an element in row i and column j of an array A would be accessed by double indexing (A[i][j] in typical notation). This way of emulating multi-dimensional arrays allows the creation of ragged or jagged arrays, where each row may have a different size — or, in general, where the valid range of each index depends on the values of all preceding indices.
This representation for multi-dimensional arrays is quite prevalent in C and C++ software. However, C and C++ will use a linear indexing formula for multi-dimensional arrays that are declared as such, e.g. by int A[10][20] or int A[m][n], instead of the traditional int **A.[6]:p.81
For an example of a language supporting multidimensional arrays, see here.

C does not have multidimensional arrays but C have arrays of arrays.
In the Standard, the wording multidimensional array is used but C multidimensional arrays are in reality arrays of arrays. From Kernighan & Ritchie:
"In C, a two-dimensional array is really a one-dimensional array, each of whose elements is an array."
Some languages support multidimensional arrays as first class types. The "Expert C Programming" book shows the example of Ada which supports both arrays of arrays and multidimensional arrays.

I get his point. He actually differ them from implementation point of view, but both are actually valid to be said multidimensional arrays.
The "array of array" kind uses linear indexing as it's actually implemented as one dimensional array, despite at language level it's referenced via multiple index. Ex, in C:
int a[5][5];
would actually have the same structure as:
int a[25];
The compiler would translate an access such as:
a[i][j]
to:
a[i * jDimensionWidth + j]
where jDimensionWidth = 5 in above example. And it's even possible to access it like:
int* b = (int*) a;
printf("%d\n",b[12] == a[2][2]); // should output 1
The "multidimensional array" kind is implemented through Iliffe vector as he said, where the indexing can't be linearized because the address is not linear as well since the vector is typically implemented as heap object. This kind of multidimensional array doesn't fit the equation (for 2-dimensional array):
addr(a[i + 1]) = addr(a[i]) + (a[i].width * sizeof(a[i][j].datatype))
which is fulfilled by the "array of array" kind.

Related

memcpy for multidimensional array

Is there a way we can copy every element from one multidimensional array to another multidimensional array by just doing one memcpy operation?
int array1[4][4][4][4];
int array2[4][4][4][4];
int main()
{
memset(&array1,1,sizeof(array1));
memset(&array2,0,sizeof(array2));
printf_all("value in array2 %d \n",array2[1][1][1][1]);
memcpy(&array2,&array1,sizeof(array2));
printf("memcopied in array2 from array1 \n");
printf("value in array2 %d \n",array2[1][1][1][1]); //not printing 1
}
Your code is correct. You should not expect the output to show you a value of 1. You should expect it to show you a value of 16843009, assuming a 4 byte int.
The reason is: you are filling array1 with bytes of value 1, not with ints of value 1. i.e. binary 00000001000000010000000100000001 (0x01010101) is being filled into all the int elements with your memset operation.
So regardless of the size of int on your machine (unless it's a single byte!) you should not expect to see the value 1.
I hope this helps.
Yes, your code should already be correct.
You have to consider memory layout when doing this. The arrays are all in one block, multi dimensional is essentially a math trick done by the compiler.
Your code says copy this memory content to the other memory block. since both share the same layout they will contain the same values.
The following code also just copies the values, but access is handled differently so you would have to think about how to get the order of elements correct.
int array1[4][4][4][4]; //elements 256
int array2[256];
int main()
{
memcpy(&array2,&array1,sizeof(array1)); //will also copy
// original access via: a + 4 * b + 16 * c + 64 * d
}
Multidimensional array in C is a flat block of memory with no internal structure. Memory layout of a multidimensional array is exactly the same as that of a 1-dimensional array of the same total size. The multidimensional interface is implemented through simple index recalculation. You can always memcpy the whole multidimensional array exactly as you do it in your code.
This, of course, only applies to built-in multidimensional arrays, explicitly declared as such (as in your code sample). If you implement a hand-made multidimensional array as an array of pointers to sub-arrays, that data structure will not be copyable in one shot with memcpy.
However, apparently you have some misconceptions about how memset works. Your memset(&array1,1,sizeof(array1)); will not fill the array with 1s, meaning that your code is not supposed to print 1 regardless of which array you print. memset interprets target memory as an array of chars, not as an array of ints.
memset can be used to set memory to zero. As for non-zero values, memset is generally unsuitable for initializing arrays of any type other than char.

C Large Two Dimensional Array Creation

****New to C!****
I am running Dev-C++ 4.9.9.2 on Windows 7 (64 bit build)
My computer has 39GB of Physical Memory.
I am trying to create a large two dimensional array. I have already created code that tells me how many dimensions it has, and how many items are in each dimension.
As an example, let's say the array is two dimensional: One million items long, and 6 wide:
[1,2,3,4,5,6],
[1,2,3,4,5,6],
[1,2,3,4,5,6],
...and on to one million items.
I have tried:
float MyArray[1000000][6];
but this crashes Dev-C. It seems to fail when I try to initialize an array larger than:
float Myarray[86486][6];
I imagine I am experiencing a "stack overflow" which amuses me since that is the name of this site.
I have been digging around and it seems I need to use malloc to help C understand how much memory to reserve. I have seen good examples of how to use this to set up a 1 dimensional array, but I would very much appreciate example code of how to set this up with a 2 dimensional array.
I have seen the example here: Initializing a large two dimensional array in C
But I'm afraid I am too much of a beginner in c to understand the brief explanation.
As background: I am coming from python where you can make an array of (almost) any size or dimension by just declaring MyArray=[] and then filling it with whatever you want.
Thank you!
Yeah, you're running up against the limit of the size of an individual stack frame.
Here's one approach:
#include <stdlib.h>
...
int main(void)
{
/**
* declare myArray as a *pointer* to a 6-element array of float
*/
float (*myArray)[6];
/**
* dynamically allocate space for 1 million objects of type
* "6-element array of float"
*/
myArray = malloc(sizeof *myArray * 1000000);
...
myArray[i][j] = ...;
}
Why this works:
The subscript operation a[i] is interpreted as *(a + i); that is, we compute the address of the i'th element (not byte) after a (the base address of the array) and dereference it. Since myArray is a pointer to a 6-element array of float, myArray[i] gives us the address of the i'th 6-element array of float after myArray.
The advantage of this approach is that the memory is allocated in a contiguous chunk, and you can subscript myArray like any 2-d array.

Declaring an array of unknown size

This is not specific to any programming language, the problem is "find the index of a specified value in an array of n numbers.
Now my question is, in the code below can you declare an array how I have done it.
{int n;
read(n);
int array[n];
......
or is this allowed?
{int n; array[n];
read(n)
I'm thinking the first one is correct.
Thanks in advance.
Converted from a comment as suggested by Merlyn Morgan-Graham
The way an array is declared depends on what language you use. If you are writing pseudo-code you can decide it yourself as long as it communicates the intent and the desired result.
The array can be declared as array = [], int[] array = new int[], int array[], array = array(), ´array = {}` etc. In some languages you have to declare the size of the array beforehand and in some languages the arrays expand when needed
In terms of syntax - that would certainly be programming language dependent. But assuming the programming language behaves more or less statically and treats arrays as statically allocated blocks in memory (rather than vectors, etc.), etc. then the first option must be correct as only after n is read a static array can be allocated.
Of course the first one is correct. In the second one when you declare the array, n is not yet set. So it is not correct.
Normally when creating an array you need to know the size before-hand. Whether you know the value at compile-time or run-time can be dependent on your language/project requirements, but it must be known before you can decide to create an array of that size. (i.e. the first solution is correct)

What is the reason C compiler demands that number of columns in a 2d array will be defined?

given the following function signature:
void readFileData(FILE* fp, double inputMatrix[][], int parameters[])
this doesn't compile.
and the corrected one:
void readFileData(FILE* fp, double inputMatrix[][NUM], int parameters[])
my question is, why does the compiler demands that number of columns will be defined when handling a 2D array in C? Is there a way to pass a 2D array to a function with an unknown dimensions?
thank you
Built-in multi-deminsional arrays in C (and in C++) are implemented using the "index-translation" approach. That means that 2D (3D, 4D etc.) array is laid out in memory as an ordinary 1D array of sufficient size, and the access to the elements of such array is implemented through recalculating the multi-dimensional indices onto a corresponding 1D index. For example, if you define a 2D array of size M x N
double inputMatrix[M][N]
in reality, under the hood the compiler creates an array of size M * N
double inputMatrix_[M * N];
Every time you access the element of your array
inputMatrix[i][j]
the compiler translates it into
inputMatrix_[i * N + j]
As you can see, in order to perform the translation the compiler has to know N, but doesn't really need to know M. This translation formula can easily be generalized for arrays with any number of dimensions. It will involve all sizes of the multi-dimensional array except the first one. This is why every time you declare an array, you are required to specify all sizes except the first one.
As the array in C is purely memory without any meta information about dimensions, the compiler need to know how to apply the row and column index when addressing an element of your matrix.
inputMatrix[i][j] is internally translated to something equivalent to *(inputMatrix + i * NUM + j)
and here you see that NUM is needed.
C doesn't have any specific support for multidimensional arrays. A two-dimensional array such as double inputMatrix[N][M] is just an array of length N whose elements are arrays of length M of doubles.
There are circumstances where you can leave off the number of elements in an array type. This results in an incomplete type — a type whose storage requirements are not known. So you can declare double vector[], which is an array of unspecified size of doubles. However, you can't put objects of incomplete types in an array, because the compiler needs to know the element size when you access elements.
For example, you can write double inputMatrix[][M], which declares an array of unspecified length whose elements are arrays of length M of doubles. The compiler then knows that the address of inputMatrix[i] is i*sizeof(double[M]) bytes beyond the address of inputMatrix[0] (and therefore the address of inputMatrix[i][j] is i*sizeof(double[M])+j*sizeof(double) bytes). Note that it needs to know the value of M; this is why you can't leave off M in the declaration of inputMatrix.
A theoretical consequence of how arrays are laid out is that inputMatrix[i][j] denotes the same address as inputMatrix + M * i + j.¹
A practical consequence of this layout is that for efficient code, you should arrange your arrays so that the dimension that varies most often comes last. For example, if you have a pair of nested loops, you will make better use of the cache with for (i=0; i<N; i++) for (j=0; j<M; j++) ... than with loops nested the other way round. If you need to switch between row access and column access mid-program, it can be beneficial to transpose the matrix (which is better done block by block rather than in columns or in lines).
C89 references: §3.5.4.2 (array types), §3.3.2.1 (array subscript expressions)
C99 references: §6.7.5.2 (array types), §6.5.2.1-3 (array subscript expressions).
¹ Proving that this expression is well-defined is left as an exercise for the reader. Whether inputMatrix[0][M] is a valid way of accessing inputMatrix[1][0] is not so clear, though it would be extremely hard for an implementation to make a difference.
This is because in memory, this is just a contiguous area, a single-dimension array if you will. And to get the real offset of inputMatrix[x][y] the compiler has to calculate (x * elementsPerColumn) + y. So it needs to know elementsPerColumn and that in turn means you need to tell it.
No, there's not. The situation's pretty simple really: what the function receives is really just a single, linear block of memory. Telling it the number of columns tells it how to translate something like block[x][y] into a linear address in the block (i.e., it needs to do something like address = row * column_count + column).
Other people have explained why, but the way to pass a 2D array with unknown dimensions is to pass a pointer. The compiler demotes array parameters to pointers anyway. Just make sure it's clear what you expect in your API docs.

Performance of 2-dimensional array vs 1-dimensional array

In C, is there a difference in time and space between an m×n 2-dimensional array vs a 1-dimensional array of length m×n (for large values of m and n)? Will accessing elements be faster with a 1-dimensional array?
In C, 2-dimensional arrays are just a neat indexing scheme for 1-dimensional arrays. Just like with a 1D array, 2D arrays allocate a single block of contiguous memory, and the A[row][col] notation is similar to saying A[row*NCOLS+col].
Usually if you were to implement your own multidimensional arrays using single dimensional arrays, you'd write an indexing function:
int getIndex(int row, int col) { return row*NCOLS+col; }
Assuming your compiler inlines this function, the performance here would be precisely the same as if you used the built in 'indexing function' of 2D arrays.
To illustrate:
#define NROWS 10
#define NCOLS 20
This:
int main(int argc, char *argv[]) {
int myArr[NROWS*NCOLS];
for (int i=0; i<NROWS; ++i) {
for (int j=0; j<NCOLS; ++j) {
myArr[getIndex(i,j)] = i+j;
}
}
return 0;
}
Should perform the same as this:
int main(int argc, char *argv[]) {
int myArr[NROWS][NCOLS];
for (int i=0; i<NROWS; ++i) {
for (int j=0; j<NCOLS; ++j) {
myArr[i][j] = i+j;
}
}
return 0;
}
Though as AraK pointed out, if you are jumping around rows a lot, and the rows are very large, you could hit a lot of page faults... in that case the custom indexing function (with rows and cols switched around) could help, but so could simply changing which of the dimensions in a 2-dimensional array you treat as the rows and which you treat as the columns.
Actually, if you use the so-called two-dimensional array in C, the compiler will do the mapping into one-dimensional array for you. If you use one-dimensional array and you like to treat it as a two-dimensional one, then you have to write the mapping yourself.
The only thing that you have to take care of is you should access the array row-wise, because the C compiler will store your two-dimensional array row after row. If you access a 'big' two-dimensional array column-wise then page-faults are likely to happen. Even if you are programming in language that supports only one-dimensional arrays, you could easily write the mapping into any number of dimensions.
Take a look at this Wikipedia article if you want to do the mapping row-wise. Your mapping could be column-wise, like FORTRAN matrices for example.
Robert is correct. Indexing expressions are compiled to pointer arithmetic expressions and so there's no difference.
What can have an impact is access order however, and so you may want to implement things yourself so you can control the access order. For example column first vs row first forms.
On modern processors, accessing large arrays at various strides can have unexpected performance differences. Sequential access is always fastest, and other strides can be up to 30 times slower due to cache interactions. Multi dimensional arrays where the inner dimensions are a power of two often have poor performance because of they way they interact with the cache associativity. To understand these issues there's no real substitute for doing measurement.
I don't think there's any difference. Internally, c treats a two dimensional array like several one-dimensional arrays in sequence.
However, as with all things performance, your mileage may vary. There may be some kind of subtle pointer arithmetic difference. Run timed tests on both scenarios. Whichever one runs faster wins.
As said by other, the difference really is how you access your items: what matters if how your items are layout in the memory, which is linear, at least on common architectures. So all you have really is 1d array, the 2d, etc... is "just" a convenience, and a reasonable compiler should optimize the indexing - but in practice, once you have more than a few variables, compilers often fail on arch like x86 because of the register starvation.
Now, it depends on your application, but I think you should think with a 1d layout by default, especially, if you need to handle multiple dimensions. The first problem with multi-dimensional arrays in C is that you cannot dynamically allocate them - if you allocate on a per-row basis, you will have awful performances because you don't have a contiguous piece of memory. See the FFTW doc for details about this.
Note that you can always describe your single piece of memory with convenient array indexing on top of it (you allocate one big nxm memory block, and then create an array of n pointer to each row).
I'm only guessing, but I would say that a 1d array is faster than a 2d array. However, it wouldn't be measurably faster. Kind of like $1,000,000.01 is more than $1,000,000.
I'd use whatever is easier to code with.

Resources