Re: Some doubts on variable-length array
- From: Ben Bacarisse <ben.usenet@xxxxxxxxx>
- Date: Fri, 31 Mar 2006 17:04:26 +0100
On Fri, 31 Mar 2006 02:00:45 -0800, lovecreatesbeauty wrote:
I can understand the behaviour of these statements marked `/* A. don't
understand */' in following code, but do not understand the statements
marked `/* B. understand */' .
Did you mean it that way round? I've commented on both just in case.
#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]);
prints the 2nd element of the 2nd element of tab.
}
int main()
{
/* int tab[9] = {0, 1, 2, 3, 4, 5, 6, 7, 8}; */
int tab[3][3] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
My compiler (gcc 4.0.1) warns me I should write:
int tab[3][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}};
although it accepts the flat list as well.
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.
printf("%i\n", tab[2][2]); /* B. understand */
The declaration of tab is in scope here so there should be no confusion.
The third element of the third element of tab is 8.
printf("%i\n", *(*(tab+2)+2)); /* B. understand */
This is another way to write the same thing. The array name tab is
treated as a pointer to its first element (an array of three ints).
Adding 2 to this pointer (tab + 2) moves it by two "strides" to make a
pointer that points to the third element (another array of three ints).
*(tab + 2) is this array, but again, the array is treated as a pointer to
its first element (an int). Adding 2 to that gives a pointer that points
to the number 8. The final * de-references that pointer to give the value
8.
printf("\n\n");
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.
printf("%i\n", tab[3][3]); /* B. understand */
printf("%i\n", *(*(tab+3)+3)); /* B. understand */
These two are exactly as above, but the array is being index out of bounds
so you get undefined behaviour (probably a segmentation fault, or maybe
just garbage being printed).
printf("\n\n");
return 0;
}
--
Ben.
.
- Follow-Ups:
- Re: Some doubts on variable-length array
- From: lovecreatesbeauty
- Re: Some doubts on variable-length array
- References:
- Some doubts on variable-length array
- From: lovecreatesbeauty
- Re: Some doubts on variable-length array
- From: lovecreatesbeauty
- Some doubts on variable-length array
- Prev by Date: Re: How to Identify functions in a .C File??
- Next by Date: Re: size in kbytes?
- Previous by thread: Re: Some doubts on variable-length array
- Next by thread: Re: Some doubts on variable-length array
- Index(es):
Relevant Pages
|
|