A
A
Alexandra2015-02-12 21:24:51
C++ / C#
Alexandra, 2015-02-12 21:24:51

How to put an n-dimensional array into a function argument?

----------------------------------------------

Answer the question

In order to leave comments, you need to log in

4 answer(s)
J
jcmvbkbc, 2015-02-12
Tsydypova @suigetsu

Well, again, experts advise adding asterisks and pointers to pointers ):
All examples below pass a three-dimensional array to the function and assign v the value of its element p[1][2][3].
If the function takes an array of fixed dimensions, then you can write it directly like this:

int f(int p[][20][30])
{
    int i = 1, j = 2, k = 3;
    int v = p[i][j][k];
}
...
int p[10][20][30];
f(p);

The first dimension (the highest one) can be omitted.
If not, then you have the following choice:
- you have the old C standard (pre-C99) - pass a pointer to the very first element and dimension values. Inside the function, recalculate the set of indexes of the multidimensional array into a linear index:
int f(int *p, int n2, int n3) // p[][n2][n3]
{
    int i = 1, j= 2, k = 3;
    int v = p[(((i * n2) + j) * n3) + k]; // v = p[i][j][k];
}
...
int p[10][20][30];
f(&p[0][0][0], 20, 30);

- you have C99 or newer: use the language support:
int f(int n2, int n3, int p[][n2][n3])
{
    int i = 1, j = 2, k = 3;
    int v = p[i][j][k];
}
...
int p[10][20][30];
f(20, 30, p);

S
Sergey, 2015-02-12
Protko @Fesor

but the compiler does not swallow.

hihi
A pointer to a pointer... and everything will pass.

A
Andrey Akimov, 2015-02-12
@Ostan

Something like this:
int function(int [2][3][4][5]); // maybe not all dimensions need to be specified, I don't remember exactly
or
int function(int ******); // the number of stars determines the price of cognac the number of array dimensions
In general, more than two stars is undesirable, you can get confused.

M
mayorovp, 2015-02-13
@mayorovp

otvety.google.ru/answer/thread?tid=1c49bd553ef14974

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question