Ben Bacarisse wrote:
> 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.
Thank you.
How is it going whan I add `foo(0, 0, tab)' and `foo(1, 1, tab)' in the
code snippet as following?
Can I think each function call refers to the array element as following
(I get inspired on it form another people goodluckyxl):
foo(0, 0, tab) refers to: tab[1+sizeof(int[0])/sizeof(int)] or
tab[1+0/sizeof(int)]
foo(0, 0, tab) refers to: tab[1+sizeof(int[1])/sizeof(int)]
foo(0, 0, tab) refers to: tab[1+sizeof(int[2])/sizeof(int)]
foo(0, 0, tab) refers to: tab[1+sizeof(int[3])/sizeof(int)]
#include <stdio.h>
void
foo(int size_x, int size_y, int tab[size_x][size_y])
{
printf("tab[1][1] == %d\n", tab[1][1]);
}
int
main()
{
int tab[9] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
foo(0, 0, (int(*)[0])tab); /* foo(0, 0, tab); */
foo(1, 1, (int(*)[1])tab); /* foo(1, 1, tab); */
foo(2, 2, (int(*)[2])tab);
foo(3, 3, (int(*)[3])tab);
return 0;
}