Re: Some doubts on variable-length array
- From: Ben Bacarisse <ben.usenet@xxxxxxxxx>
- Date: Fri, 31 Mar 2006 19:23:22 +0100
On Fri, 31 Mar 2006 09:12:25 -0800, lovecreatesbeauty wrote:
Ben Bacarisse wrote:
foo(2, 2, tab); /* A. don't understand */
This calls "lies" to foo telling it that the array is 2x2 so foo sees it
as if it were "int tab[2][2] = {{0, 1}, {2, 3}};". Element [1][1] is 3
and this is what is printed.
I know it before that functions regard an array argument same as a
pointer. So how can the layout/dimension of an actual array argument be
known inside the function body? Are new meanings/semantics given to
array arguments when they are variable-length array?
Yes. The special syntax of these arguments lets the compiler know how big
each row of the parameter array is.
foo(3, 3, tab); /* A. don't understand */
This call does not "lie". So inside foo it is seen as it was defined and
element [1][1] is the number 4.
The original array is: /* int tab[9] = {0, 1, 2, 3, 4, 5, 6, 7, 8}; */
, if it is used instead, then foo(3, 3, tab); lies again, right?
Yes and this is a bigger lie. But I put "lie" in quotes, because it may
be OK to do it. Telling a function the "shape" of the data array is fine
so long as you know what will happen when you do that.
If you want to treat a flat array as a collection of rows, then you are
free to do so but you will need to persuade the compiler with a cast in
the call to foo: foo(3, 3, (int (*)[3])tab) and you will not be able to
write tab[2][2] within scope of the flat definition. Nor will the mess
with all the pointer arithmetic work. In short, you need a very good
reason to go messing about like that. If you have 2D array, then just
declare it and use it. Pass at least the "row size" to any functions that
use the array and all will be fine. Passing both sizes makes sense for
many applications and helps to document the code.
--
Ben.
.
- References:
- Some doubts on variable-length array
- From: lovecreatesbeauty
- Re: Some doubts on variable-length array
- From: lovecreatesbeauty
- Re: Some doubts on variable-length array
- From: Ben Bacarisse
- Re: Some doubts on variable-length array
- From: lovecreatesbeauty
- Some doubts on variable-length array
- Prev by Date: A question on variable defination
- Next by Date: Re: A question on variable defination
- Previous by thread: Re: Some doubts on variable-length array
- Next by thread: How to Identify functions in a .C File??
- Index(es):
Relevant Pages
|