c++ - 指针算术(带强制转换的指针减法)

标签 c++ c pointers pointer-arithmetic

为什么执行结束时的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/

相关文章:

c - C 中 Switch-Case 的意外行为

c++ - 将指向结构的 void 指针或 memcpy 转换为新结构?

c++ - 动态上下文相关运算符的设计模式(例如模运算)?

c++ - c++中文字常量的存储

c++ - 将嵌套的基模板类实例声明为派生类的 friend

c++ - Biicode (biicode.conf) 中的#include 语句映射

c - 来自不兼容指针类型 c 的赋值

c - 字符串附加功能不起作用

c++ - 为什么这个指针不是 NULL,尽管它从未被初始化?

c - 使用结构体指针读取成员变量