减去两个指针给出意外结果 [英] Subtracting two pointers giving unexpected result

查看:92
本文介绍了减去两个指针给出意外结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>

int main() {
    int *p = 100;
    int *q = 92;
    printf("%d\n", p - q);  //prints 2
}

上面程序的输出不应该是8吗?

Shouldn't the output of above program be 8?

我得到2.

推荐答案

除了未定义的行为,这是您使用指针算术得到的行为:当合法减去指针时,它们的差代表指针之间的数据项数.指针.如果int在您的系统上每个int使用四个字节,则指针之间相隔八字节的差为(8 / 4),这等于2.

Undefined behavior aside, this is the behavior that you get with pointer arithmetic: when it is legal to subtract pointers, their difference represents the number of data items between the pointers. In case of int which on your system uses four bytes per int, the difference between pointers that are eight-bytes apart is (8 / 4), which works out to 2.

这是一个没有未定义行为的版本:

Here is a version that has no undefined behavior:

int data[10];
int *p = &data[2];
int *q = &data[0];
// The difference between two pointers computed as pointer difference
ptrdiff_t pdiff = p - q;
intptr_t ip = (intptr_t)((void*)p);
intptr_t iq = (intptr_t)((void*)q);
// The difference between two pointers computed as integer difference
int idiff = ip - iq;
printf("%td %d\n", pdiff, idiff);

演示.

这篇关于减去两个指针给出意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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