为什么执行结束时的j是“1”? 在 64 位 Unix 机器上使用以下标志 gcc -m32 xxx.c 进行编译。
#include <stdio.h>
int main(int argc, char **argv)
{
int *q = (int *)2;
char *r = (char *)1;
int j;
q++;
r++;
j = (int *)q - (int *)r;
printf("j = %d\n", j);
return 0;
}
代码仅用于学术目的! ;)
最佳答案
首先,理论上这都是未定义的行为,因为您使用的是指向未分配内存的指针,比较不属于同一数组的内容等。
现在,把这个放在一边,一旦你清楚了指针算术的机制,那就很容易了:
int *q = (int *)2;
char *r = (char *)1;
int j;
// a pointer is incremented in steps of the size of its "base type"; this
// allows to move to the next element if you are pointing inside an array
q++; // q=(int*)(2+sizeof(int))=(int *)6
r++; // r=(char *(1+sizeof(char))=(int *)2;
// again, the difference between two pointers is computed in units of the
// base type; in an array, this gives you how many places are two elements
// apart
j = (int *)q - (int *)r; // (6-2)/sizeof(int)=1
(此处 sizeof(int)
为 4,因为您使用 gcc 和 -m32
进行编译,而 sizeof(char)
为 1 sizeof
的定义)
关于c++ - 指针算术(带强制转换的指针减法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24098526/