gpt4 book ai didi

c - 存储指针的整数差异?

转载 作者:太空宇宙 更新时间:2023-11-04 03:54:20 25 4
gpt4 key购买 nike

这是代码:

#include<stdio.h>
#include<conio.h>

int main()
{
int *p1,*p2;
int m=2,n=3;
m=p2-p1;
printf("\np2=%u",p2);
printf("\np1=%u",p1);
printf("\nm=%d",m);
getch();
return 0;
}

输出如下:

p2= 2686792
p1= 1993645620
m= -497739707

我对代码和输出有两个疑问:

  1. 由于“m”是一个整数,它不应该将 p2-p1 作为输入,因为 p1 和 p2 都是指针,而 m 是一个整数,它应该给出一个错误,如“从 'int' 进行的无效转换”到'int'“但事实并非如此。为什么?

  2. 即使在接受输入之后,差异也是无效的。这是为什么?

最佳答案

Since 'm' is an int, it shouldn't take p2-p1 as an input since p1 and p2 both are pointers and m is an integer it should give an error like "invalid conversion from 'int' to 'int' " but it isn't. why?

这种类型的错误或警告取决于您使用的编译器。 C 编译器经常给程序员足够的绳索来吊死自己...

Even after it takes the input, the difference isn't valid. Why is it?

其实,区别是对的!它使用 pointer arithmetic 来执行计算。所以对于这个例子..

p2=2686792

p1=1993645620

由于指针没有被初始化,它们被分配了一些像上面那样的垃圾值。现在,您想执行操作 p2 - p1,即您要求的内存地址恰好位于 p2 之前的 p1 内存块。由于 p1 和 p2 是指向整数的指针,因此内存块的大小为 sizeof(int)(几乎总是 4 个字节)。因此:

p2 - p1 = (2686792 - 1993645620)/sizeof(int) = (2686792 - 1993645620)/4 = -497739707

关于c - 存储指针的整数差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18108872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com