About two dimensional arrays in C--> Is array[1][0] and array[0][1] the same?
int main ()
{
int arr[10][1];
arr[1][0]=44;
arr[0][1]=55;
printf("%i",arr[1][0]);
return 0;
}
Should this print out "55"开发者_如何学Python or "44"???
There is no such element as arr[0][1]
-- just as there is no element arr[10][0]
-- array indices are zero based.
If you declare:
int arr[10][2];
Your code will work as you intended.
With the declaration
int arr[10][1];
when you access arr[0][1]
you are accessing beyond the end of the first array "row." Memory access in C is not checked, so your access aliases the element stored at arr[1][0]
.
If you swapped the order of the two assignment statements, you would see that the value displayed depends on the order of those two assignments. The later assignment writes over the value from the earlier assignment. I.e.:
int main ()
{
int arr[10][1];
arr[0][1]=55;
arr[1][0]=44;
printf("%i",arr[1][0]);
return 0;
}
...would print 44, simply because that would be the final value written to that int-sized spot in memory.
EDIT: Because we have so many people commenting here, claiming to interpret the lousy C99 standard as declaring the behavior you have invoked as "undefined behavior"... Consider that the following code does the same thing as above, due to section 6.5.2.1:
int main(int argc, char *argv[])
{
int arr[10][1];
arr[1][0] = 44;
arr[0][1] = 55;
printf("Value is: %d\n", 0[arr][1]);
return 0;
}
In a linked question, the claim has been made that the C compiler may choose to pad the space between array "rows" due to alignment concerns. That is disinformation; no C standard says that is possible.
No they are not the same. You declared an array of ten arrays each with a single integer element. arr[0][1]
is greater than your array index so should be an error. The result should be 44.
精彩评论