为什么指针+ 1实际上加4 [英] Why a pointer + 1 add 4 actually

查看:199
本文介绍了为什么指针+ 1实际上加4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>
int main(void){
  int *ptr,a,b;
  a = ptr;
  b = ptr + 1;
  printf("the vale of a,b is %x and %x respectively",a,b);

  int c,d;
  c = 0xff;
  d = c + 1;
  printf("the value of c d are %x and %x respectively",c,d);
  return 0;
}

输出值为

the vale of a,b is 57550c90 and 57550c94 respectively
the value of c d are ff and 100 respectively%  

实际上是ptr + 1,为什么它表现得如此?

it turns out the ptr + 1 actually, why it behave this way?

推荐答案

考虑指针是什么...它是一个内存地址.存储器中的每个字节都有一个地址.因此,如果您有一个4个字节的int并且其地址是1000,则1001实际上是该int的第二个字节,而1002是第三个字节,而1003是第四个字节.由于int的大小可能因编译器而异,因此当您增加指针时,必须不要在int中获得某个中间点的地址.因此,将根据您的数据类型确定要跳过多少个字节的工作,您可以使用获得的任何值而不必担心.

Consider what a pointer is... it's a memory address. Every byte in memory has an address. So, if you have an int that's 4 bytes and its address is 1000, 1001 is actually the 2nd byte of that int and 1002 is the third byte and 1003 is the fourth. Since the size of an int might vary from compiler to compiler, it is imperative that when you increment your pointer you don't get the address of some middle point in the int. So, the job of figuring out how many bytes to skip, based on your data type, is handled for you and you can just use whatever value you get and not worry about it.

正如Basile Starynkvitch指出的那样,该数量将根据所指向的数据成员的sizeof属性而有所不同.很容易忘记,即使地址是顺序的,对象的指针也需要考虑容纳这些对象所需的实际存储空间.

As Basile Starynkvitch points out, this amount will vary depending on the sizeof property of the data member pointed to. It's very easy to forget that even though addresses are sequential, the pointers of your objects need to take into account the actual memory space required to house those objects.

这篇关于为什么指针+ 1实际上加4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆