为什么指针+1包含的内存地址不同于所指向的值的地址+ 1 [英] Why memory address contained by pointer +1 is different from address of value being pointed + 1

查看:193
本文介绍了为什么指针+1包含的内存地址不同于所指向的值的地址+ 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

指针存储指向的值的内存地址,因此指针包含的内存地址与值的内存地址相同.因此,将这两个内存地址加1会产生相同的结果,这是没有发生的.为什么? 这是代码

Pointer stores memory address of value being pointed at so memory address contained by pointer is same as memory address of value. So adding 1 to both these memory addresses should yield same result, which is not happening. Why? Here is the code

 int main()
 {
     int ages[] = {23, 43, 12, 89, 2};
     int *cur_ages = ages;

     printf("\n&cur_ages=%p, &cur_ages+1=%p", &cur_ages, &cur_ages+1);
     printf("\n&ages=%p, &ages+1=%p", &ages, &ages+1);
     printf("\ncur_ages=%p, cur_ages+1=%p", cur_ages, cur_ages+1);
     printf("\n*cur_ages=%d, *cur_ages+1=%d", *cur_ages, *(cur_ages+1));

     return 0;
 }

输出为

&cur_ages=0x1ffff85f3d0, &cur_ages+1=0x1ffff85f3d8
&ages=0x1ffff85f3dc, &ages+1=0x1ffff85f3f0
cur_ages=0x1ffff85f3dc, cur_ages+1=0x1ffff85f3e0
*cur_ages=23, *cur_ages+1=43

& ages + 1不等于cur_ages + 1.为什么?

&ages+1 is not equal to cur_ages+1. Why?

推荐答案

指针算术将指针的值增加给定值乘以指针指向的类型的大小.

Pointer arithmetic increases the value of a pointer by the given value multiplied by the size of the type it points to.

因此,当您这样做时:

&ages+1

获取地址ages(类型为int [5])并将sizeof(ages)添加到指针值.假设sizeof(int)为4,则将指针值加20.

You take the address of ages (which is of type int [5]) and add sizeof(ages) to the pointer value. Assuming sizeof(int) is 4, this adds 20 to the pointer value.

同样,当您这样做时:

cur_ages+1

在这里,cur_ages指向int,所以加1会将sizeof(int)添加到指针值.

Here, cur_ages points to a int, so adding 1 adds sizeof(int) to the pointer value.

这篇关于为什么指针+1包含的内存地址不同于所指向的值的地址+ 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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