指针实际上是如何按类型递增的

How are pointers actually made to increment by the type their type

本文关键字:类型 何按 实际上 指针      更新时间:2023-10-16

如何使指针按类型递增。例如,如果我们有

int *ptr;       
ptr++;   //would point to the next integer i.e. it would increment ptr by 4bytes in 32 bit system

我想知道这是如何在内部完成的。

编译代码的编译器知道指针的基类型,并将代码适当地放入递增指针(偏移量)。例如:

int* p = new int[10];
*(p+2) = 100;

第二行是这样的:

p + sizeof(int) * 2 ... // Not C/C++

类似地:

p++;

意思是:

p = p + sizeof(int); // Not C/C++

如果p的类型是其他类型(如float或某种结构),则将适当地执行计算。没有魔法。类型是编译时定义的——一种类型的变量在运行时不会改变,因此计算也是如此。