Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do multidimensional arrays in C++ function? [duplicate]

Possible Duplicate:
How do I use arrays in C++?

To put it simply, is a multidimensional array in C++ an array of arrays or is it simply a single array which behaves like it's multidimensional?

A friend of mine explained that arrays in C++ are simply constant pointers, and that multidimensional arrays are also constant pointers whose elements are addressed by more than one index (i.e. they are pointers pointing to one big array, and the offset of the elements are calculated using multiple indices).

I believe that multidimensional arrays are single dimensional arrays of pointers which point to other arrays because when passing multidimensional arrays as function arguments I often use the syntax:

void copy_matrix(int ** matrix);

If not, is it possible to create an array of arrays in C++ and assign the value of each sub-array at compile time - equivalent to the semantics of the following statements:

int line[2][2];

line[0] = {100, 100};
line[1] = {200, 200};

The above statements generate a compile time error. A quick (untested) hack I came up with was:

int line[2][2];

void assign(int index, int * point, int length) {
    for (int i = 0; i < length; i++) {
        line[index][i] = point[i];
    }
}

assign(0, {100, 100}, 2);
assign(1, {200, 200}, 2);

However, I believe that there must be a more elegant way to achieve the same result. I hope to clearly understand these concepts, and any input is appreciated.

like image 895
Aadit M Shah Avatar asked Apr 23 '26 22:04

Aadit M Shah


1 Answers

The brace-list initializer only works during initialization, and it cannot be used for assignment, as you seem to attempt.

Instead, just initialize the multi-dimensional array all at once:

int line[2][2] = { {100, 100}, {200, 200} };

In response to your first sentence: Arrays are arrays and pointers are pointers, and they're not the same thing. An array does however decay to a pointer to the first element with ease, and x[n] is equivalent to *(x + n). This applies recursively to multi-dimensional arrays as well.

Arrays T[N] are contiguous in memory for T and sizeof(T[N]) == N * sizeof(T); therefore, arrays of arrays T[N][M] are contiguous both for T[N] and for T.

like image 75
Kerrek SB Avatar answered Apr 25 '26 12:04

Kerrek SB