注册 登录
编程论坛 C++教室

两个数组指针的正误

cclearner 发布于 2007-07-05 17:51, 517 次点击
#include <iostream>
using namespace std;
int main()
{
int a[10]={1,2,3,4,5,6,7,8,9,0};
int i;
for(i=0; i<10; i++)
cout<<*(a+i*sizeof(int))<< " ";
cout<<endl;
}

#include <iostream>
using namespace std;
int main()
{
int a[10]={1,2,3,4,5,6,7,8,9,0};
int i;
for(i=0; i<10; i++)
cout<<*(a+i)<< " ";
cout<<endl;
}

这两个写法,哪个对?

按照运行结果看是第二个啊
5 回复
#2
HJin2007-07-05 19:40

1st version is wrong.

a --- gives the address of item
a + 1 give the address of 2nd item.
a + 1*sizeof(int) = a +4 = 5th item.

#3
cclearner2007-07-05 20:08

Thanks a million!
But English......
Mine is very poor!

#4
野比2007-07-05 22:35

哈哈... cclearner... 有意思哦...
第一个版本若在汇编里是对的.. 因为汇编的偏移单位固定为1 byte
版本2是正确的..因为C里面偏移实际上不是真正的偏移.. 它的偏移单位根据变量的具体类型来决定,
相当于自带了 *sizeof(数据类型)
...这样的..

#5
cclearner2007-07-05 23:33
嗯,懂了
两个帖子参照着看,非常得明白
#6
野比2007-07-05 23:46
懂了就好... 这个和你问的那个引用问题差不多..
1