如果你加1的指针,它真的加1呢,还是加4或32? [英] If you add 1 to a pointer, does it really add 1, or does it add 4 or 32?

查看:184
本文介绍了如果你加1的指针,它真的加1呢,还是加4或32?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一个指针,通过产生的东西像

Suppose you have a pointer, produced by something like

int a = 5;
int* pointer = &a;

和假设你在

pointer = pointer + 1;

现在假设指示器的原始按位重新presentation是

Now suppose the original bitwise representation of the pointer was

00000000 00000000 00000000 00000000

然后就是新的再presentation 00000000 00000000 00000000 00000001 ?或 00000000 00000000 00000001 00000000 ?或者两者都不是那些?

Then is the new representation 00000000 00000000 00000000 00000001? Or 00000000 00000000 00000001 00000000? Or neither of those?

我很困惑,因为我觉得加1的号码时加1,其按位重新presentation。但是,如果你加1,数组的索引,新的地址是从旧地址32位了。

I am confused because I feel like adding 1 to a number should add 1 to its bitwise representation. But if you add 1 to the index of an array, the new address is 32 bits away from the old address.

推荐答案

这取决于指针的类型。

,指针实际上都是相同的,就实际的数据而言。一个为int * 将同一类的数据作为的char * 的(整数重新presenting内存位置) 。为什么我们关心的数据类型的指针指的是,除了知道如何去code将其(即取消对它的引用)的原因,要知道如何指向同一类型的下一个元素。所以,让 P 是指向一个对象(对象不是作为空中接力,但作为具有相关联的一些存储的任何变量)键入 T <的/ code>。然后,使用intptr_t(P + 1)=使用intptr_t(P)+的sizeof(T)

The pointer actually are all the same, as far as the actual data is concerned. An int* keeps the same kind of data as a char* (integer values representing memory locations). The reason why we care about the kind of data a pointer points to is, besides knowing how to decode it (i.e. dereference it), to know how to point to the next element of the same type. So, let p be a pointer to an object (object not as in oop, but as any variable that has some storage associated) of type T. Then, intptr_t(p + 1) = intptr_t(p) + sizeof(T).

这是特别有用,在使用数组时,如果​​你想一点点,这是有道理的。考虑声明为int * p = 0x100的,并假设在地址100是一种有效的整数值。它将使什么意义,从0x101访问整型值(这实际上是非法的,因为整数必须被4整除的地址开始 - 考虑的sizeof(int)的= 4)?

This is particularly useful in working with arrays and, if you think a little bit, it makes sense. Consider the declaration int *p = 0x100 and assume that at address 100 is a valid integer value. What sense would it make to access the integer value from 0x101 (this is actually illegal, since ints must start on addresses divisible by 4 - considering sizeof(int) = 4)?

这篇关于如果你加1的指针,它真的加1呢,还是加4或32?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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