指针运算得到的输出错误 [英] Pointer arithmetic getting wrong output
问题描述
在下面的程序,在这里, PTR
被宣布为一个指向整数指针,并分配数组的基址 P []
,已被宣布为整型指针数组。假设 PTR
包含地址 9016
(假设P的起始地址为9016)前 PTR
是递增,并在 PTR ++
,它将包含值9020(假设int接受4个字节)。
所以 PTR-P
应该给输出4即(9020-9016 = 4)。但它给输出1。为什么?
#包括LT&;&stdio.h中GT;
诠释的main()
{
静态int类型的[] = {0,1,2,3,4};
静态为int * P [] = {A,A + 1,+ 2,+ 3,+ 4};
INT ** PTR = P;
PTR ++;
的printf(%d个,PTR-P);
返回0;
}
一个指针的结果减去另一个指针的元素他们之间而不是字节数数。
INT ** PTR = P;
PTR ++;
PTR
向前移动一个元素,因此 PTR - P
的 1的值
。
顺便说一句,此行为与 PTR ++
是一致的(即 PTR = P + 1,在你的榜样
。
In the following program, Here ptr
Has been declared as a pointer to an integer pointer and assigned the base address of the array p[]
, which has been declared as an array of integer pointer. Suppose ptr
contains the address 9016
(suppose the starting address of p is 9016) before ptr
is incremented and after ptr++
, it will contain the value 9020 (suppose int takes 4 bytes).
So ptr-p
should give the output as 4 i.e (9020-9016=4). But it is giving output as 1 . why?
#include<stdio.h>
int main()
{
static int a[]={0,1,2,3,4};
static int *p[]={a,a+1,a+2,a+3,a+4};
int **ptr=p;
ptr++;
printf("%d",ptr-p);
return 0;
}
The result of one pointer minus another pointer is the number of elements between them, not the number of bytes.
int **ptr=p;
ptr++;
ptr
moves forward one element, so ptr - p
has a value of 1
.
BTW, this behavior is consistent with ptr++
(which means ptr = p + 1;
in your example.
这篇关于指针运算得到的输出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!