arrays as function arguments

J

John Bode

To add a bit of explanation... In
void f2(int (*p)[4]);
the 4 matters. The compiler needs to know how to access p[1][x] and
p[10][x] -- these need the 4 to be part of the type of p.

I am sorry, I simply don't get your explanation. Why does the 4 matter
to the compiler in this f2 case and not in f1?

With other words: O.k., I've learned that 'int p[4]' and 'int p[5]'
are simply both treated as 'int* p' (f1 case), and the compiler seems
to be satisfied since type checks are o.k. (even though it has lost
information and will not know that accessing 'p[6]' may be beyond what
was passed to f1).

However, besides the fact that 'int(*p)[4]' and 'int(*p)[5]' are
different pointer types, you mean there is another explanation besides
the difference of the pointer types -- could you be more verbose?

When an array identifier appears in an expression other than as an
operand to sizeof or &, its type is implicitly converted from "N-
element array of T" to "pointer to T", and it's value is set to point
to the first element in the array.

For example, given the array definition

int arr[5];

the type of "arr" is "5-element array of int." When "arr" appears in
an expression, its type is implicitly converted to "pointer to int",
or int *.

This is true of any N-element array of int:

int barr[10];
int carr[20];

Like "arr", whenever "barr" or "carr" appear in an expression, their
types will also be converted to "pointer to int", so they are
effectively interchangeable as function parameters, even though the
array types are all different.

Now let's look at 2-dimensional arrays:

int darr[3][4];
int earr[3][5];

The type of "darr" is "3-element array of 4-element arrays of int."
The type of "earr" is "3-element array of 5-element arrays of int."
When "darr" appears in an expression, its type is converted to
"pointer to 4-element array of int", or int (*)[4]. When "earr"
appears in an expression, its type is converted to "pointer to 5-
element array of int", or int (*)[5].

The pointer types are different, so they are not interchangeable as
function parameters. However, note that the following *would* be
interchangeable:

int farr[4][3];
int garr[5][3];

Both would be converted to the same type (pointer to 3-element array
of int).
 

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,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top