[英]Dereferenced pointer assignments
Consider the code snippet below:考虑下面的代码片段:
int *p=NULL,*t=NULL,e;
char l=65;
char *k=&l;
p=(int*)&l;
t=(int*)k;
e=*t;
printf("%d\n",*p);
printf("%d\n",*t);
printf("%d\n",e);
The output of the above snippet is as follows:上述代码段的输出如下:
16705
16705
65
Now it is evident that &l
is an address to a char and p=(int*)&l
lets an int pointer ie p point to the same location this is the same with pointer t.现在很明显
&l
是一个 char 的地址,而p=(int*)&l
让一个 int 指针即 p 指向相同的位置,这与指针 t 相同。 Now if I dereference p rightly so it will try to dereference 4 consecutive memory blocks (assuming int points to 4 bytes) and print out a garbage value of sorts which happens for *t
as well but when I print e I get 65 back which is confusing to me as e=*t
which should be same as *p
or *t
perhaps?现在,如果我正确地取消引用 p ,那么它将尝试取消引用 4 个连续的内存块(假设 int 指向 4 个字节)并打印出
*t
也发生的各种垃圾值,但是当我打印 e 时,我得到 65,这是令我困惑的是e=*t
应该与*p
或*t
相同吗?
Dereferencing p
(ie using *p
) is undefined behavior as there isn't an int
at that location.取消引用
p
(即使用*p
)是未定义的行为,因为该位置没有int
。 Anything may happen... and no one can explain the output you get.任何事情都可能发生……没有人可以解释你得到的输出。
Compiling your code with "gcc -Wall -Wextra -pedantic ..." gives me:用“gcc -Wall -Wextra -pedantic ...”编译你的代码给了我:
main.cpp:19:1: warning: array subscript 'int[0]' is partly outside array bounds of 'char[1]' [-Warray-bounds]
19 | printf("%x\n",*p);
which directly tells you that the program has problems that needs to be fixed.它直接告诉您该程序存在需要修复的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.