两个指针变量之间的差异 [英] Difference between two pointer variables

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

问题描述

我在笔试中问过这个问题. 在我的lapi上运行以下代码时,我的输出为10

i have asked this question in a written test. while running the below code on my lapi, i am getting 10 as output

#include<stdio.h>
int main()
{
  int *i, *j;/* two pointer variable*/
  i = (int *)60;
  j = (int *)20;
  printf("%d \n",i-j);
  return 0;
}

输出:

10 

谁能告诉我为什么输出是10.

Can anyone tell me why the output is 10.

推荐答案

根据C标准(6.5.6加法运算符)

According to the C Standard (6.5.6 Additive operators)

9当两个指针相减时,都应指向的元素 相同的数组对象,或者在数组的最后一个元素之后 对象; 结果是两者下标的差异 数组元素.

9 When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements.

因此您的程序具有未定义的行为,因为指针没有指向同一数组的元素.

So your program has undefined behaviour because the pointers do not point to elements of the same array.

无论如何,似乎编译器只是生成一个用于减去两个指针的目标代码,而与指针是否指向同一数组的元素无关(它信任您).

Nevertheles it seems that the compiler simply generates an object code for subtracting two pointers irrespective of whether the pointers point to elements of the same array (it trusts you).

在这种情况下,根据指针算法的不同,两个指针之间的区别是两个指针之间可以放置在内存中的元素数.

In this case the difference between the two pointers according to the pointer arithmetic is the number of elements that can be placed in the memory between two pointers.

在您的情况下,sizeof( int )等于4.因此,如果sizeof( int )等于4,则大小为40字节的内存可以容纳类型为int的10元素.

In your case the sizeof( int ) is equal to 4. So a memory that has size of 40 bytes can accomodate 10 elements of type int provided that sizeof( int ) is equal to 4.

此值10由printf函数输出.

This value that is 10 is outputed by the printf function.

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

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