指针/地址的区别 [英] Pointer/Address difference

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

问题描述

为什么两个地址之间的区别来错了吗?
HTTP://$c$cpad.org/NGDqFWjJ

 #包括LT&;&stdio.h中GT;
诠释的main()
{
INT I = 10,J = 20;
为int * p =&放;我;
INT * Q =&放大器;焦耳;
INT C = P-Q;
的printf(%d个\\ N,P);
的printf(%d个\\ N,Q);
的printf(%D,C);
返回0;
}

输出:

  -1083846364
-1083846368
1


解决方案

首先,在不相关的指针进行时指针运算没有定义。

第二,它是有道理的。当减去指针你获得这些地址,而不是字节数量之间的元素数。

如果你尝试以

 的char * P1 =放;我,* P2 =&放大器;焦耳;

你会得到不同的结果。


作为一个方面说明,使用%P 打印指针时。

Why is the difference between the two addresses coming 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\n", p);
printf("%d\n", q);
printf("%d", c);
return 0;
}

Output:

-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.

If you were to try that with

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

you would get a different result.


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

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

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