指针/地址差异 [英] Pointer/Address difference

查看:21
本文介绍了指针/地址差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么两个地址的区别是错误的?http://codepad.org/NGDqFWjJ

Why is the difference between the two addresses wrong? http://codepad.org/NGDqFWjJ

#include<stdio.h>
int main()
{
   int i = 10, j = 20;
   int *p = &i;
   int *q = &j;
   int c = p - q;
   printf("%d
", p);
   printf("%d
", q);
   printf("%d", c);
   return 0;
}

输出:

-1083846364
-1083846368
1

推荐答案

首先,当对不相关的指针执行时,没有定义指针算法.

First, pointer arithmetic isn't defined when performed on unrelated pointers.

其次,这是有道理的.减去指针时,您会得到这些地址之间的元素数,而不是字节数.

Second, it makes sense. When subtracting pointers you get the number of elements between those addresses, not the number of bytes.

如果你想试试

char *p1 = &i, *p2 = &j;

你会得到不同的结果.

作为旁注,打印指针时使用 %p.

As a side note, use %p when printing pointers.

这篇关于指针/地址差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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