multi dimension arrays

R

Robert

Lets say you have an multi array of ints num[x][y] and send
it as a pointer to a function X(arg) have do a do this without
define the size?

It works with X(int (*num)[0]).
Why cant I use X(int **num) ?

//Robert
 
P

Peter Pichler

Robert said:
Lets say you have an multi array of ints num[x][y] and send
it as a pointer to a function X(arg) have do a do this without
define the size?

I find it difficult to parse your question. What language is it in?
It works with X(int (*num)[0]).
Why cant I use X(int **num) ?

Define "works". In function parameter context, the two declarations above
are equivalent. Unfortunately, they are both (most probably) wrong.
Consider:

int X (int (*num)[0]);

int main (void)
{
int x[3][4];
X(x);
return 0;
}

Your 'x' is an array of three arrays of four ints, organized in memory like
this:

x[0] x[1] x[2]
+-----------------+-----------------+-----------------+
| [0] [1] [2] [3] | [0] [1] [2] [3] | [0] [1] [2] [3] |
+-----------------+-----------------+-----------------+
^ ^ ^
x[0][0] x[1][0] x[1][3] ...etc.

To get from x[0][0] to x[1][0], you need to skip exactly four ints, i.e.
sizeof x[0] (or 4*sizeof(int) if you like) bytes.

But your function X expects an array of pointers to int. Array of
unspecified size of pointers to int, to be more precise. Like this:

x[0] x[1] x[2] ...
+----+----+----+--
| *0 | *1 | *2 | ...
+----+----+----+--

To get to x[1][0], for example, you need to skip sizeof x[0] bytes as in the
first example, take the pointer from there, add an index (0 in your case)
and dereference it.

I /can/ imagine a platform where sizeof x[0] is the same in both cases, i.e.
sizeof(int*) == 4*sizeof(int), but believe me, such platforms are rare.

So, int[x][y] and int(*)[0] are not equivalent types. There was a recent
post by Chris Torek on this topic, explaining exactly how the former could
decay to the latter in a function call, but that does not make it right.
(Unfortunately I don't recall the subject of that thread, sorry.)

The correct way to declare multi-dimensional arrays in function arguments
is:

int fun (int array[][X][Y][Z]);

Add as many dimensions as you like (up to six, <g>), but only the first one
can be unspecified. Your X, Y, Z etc are the same constants that you used
for declaring the array that you pass to the function.

I hope this make sense.

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top