问题描述
int arr[3][2]={{1,2},{3,4},{5,6}};
int *c=&arr;
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
printf("\n %d %d",((arr+i)+j),*(*(arr+i)+j));
}
}
for(i=0;i<6;i++)
{
printf("\n%d",(c++));
}
output:
2293536 1
2293536 2
2293552 3
2293552 4
2293568 5
2293568 6
2293536
2293540
2293544
2293548
2293552
我不明白这一点:为什么一维数组不一样的2D?二者都存储像线性阵列。 改编[1] [0]
不一样的(ARR + 0)+1
。为什么地址在改编
?
I cannot understand this: why one dimensional array is not same as 2d? Both are stored like linear array. arr[1][0]
is not same as (arr+0)+1
. why address are different in arr
?
推荐答案
改编[1] [0]
是不一样的(ARR +0)+1
- 它从未被认为是。 改编[1] [0]
等同于 *(*(ARR + 1)+0)
,或者,如果你指的是地址,那么&放大器;常用3 [1] [0]
相同 *(ARR + 1)+ 0
。
arr[1][0]
is not the same as (arr+0)+1
- it was never supposed to be. arr[1][0]
is equivalent to *(*(arr+1)+0)
, or, if you mean the address, then &arr[1][0]
is the same as *(arr+1)+0
.
这样,你的的printf
是错误的:
printf("\n %d %d",((arr+i)+j),*(*(arr+i)+j));
记住,因为改编
是一个由2阵列3,编曲+ X
是 2 * sizeof的(INT)
字节的路程。正因为如此,要打印不匹配你解引用地址。 改编+ I + J
不是 *(*(ARR + I)+ J)
的地址。
Remember, since arr
is a 3 by 2 array, arr+x
is 2*sizeof(int)
bytes away. Because of that, you are printing addresses that don't match what you dereference. arr+i+j
is not the address of *(*(arr+i)+j)
.
如果您想打印的地址后面是什么在那里,你应该使用这样的:
If you want to print the address followed by what is in there, you should use this instead:
printf("\n %p %d", (void *) *(arr+i)+j,*(*(arr+i)+j));
请注意格式说明%P
。它必须是 *(ARR + I)+ J
,而不是(ARR + I)+ J
,因为 *(ARR + I)
的类型为为int *
- 这是一个指向第一个元素常用3 [I]
。
Note the format specifier %p
. It must be *(arr+i)+j
, and not (arr+i)+j
, because *(arr+i)
is of type int *
- it's a pointer to the first element in arr[i]
.
你的第二个的printf
电话:
printf("\n %d %d",(c++));
是无效的:你指定两个格式说明,只有一个提供
Is invalid: you specify two format specifiers and provide only one.
这篇关于用C一维和二维数组之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!