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

查看:36
本文介绍了为什么指针 + 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?

推荐答案

考虑一下什么是指针……它是一个内存地址.内存中的每个字节都有一个地址.所以,如果你有一个 int 是 4 个字节,它的地址是 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天全站免登陆