int a[5];
cout << &a[1] << " " << &a[0] << endl;
cout << (&a[1] - &a[0]);
在上面的代码,这是为什么&一[1] - &一个[0]等于1,而不是4?这些地址之间不应该有4个字节,因为我们有一个int数组?C++指针运算
int a[5];
cout << &a[1] << " " << &a[0] << endl;
cout << (&a[1] - &a[0]);
在上面的代码,这是为什么&一[1] - &一个[0]等于1,而不是4?这些地址之间不应该有4个字节,因为我们有一个int数组?C++指针运算
不,指针差异在元素中,而不是在字节中。
为了得到它以字节为单位(现场观看https://ideone.com/CrL4z)
int a[5];
cout << (a+1) << " " << (a+0) << endl;
cout << (reinterpret_cast<char*>(a+1) - reinterpret_cast<char*>(a+0));
哎呀,没人看到那个忍者编辑我希望? – sehe
指针由有型的规模递增。原因是因为你想指向下一个项目。所以让你更进一步。
int a[5];
int *ptr=&a[0];
// ptr is now pointing at first element.
ptr+3; // now its pointing at 3rd element.
那么简单。 @ user974967:从长远看书会便宜 – sehe