例如程序:
c
#include <stdio.h> int *return_sth() { int tmp = 5; int *ptr = &tmp; return ptr; } int main(void) { printf("%p, %d\n", return_sth(), *return_sth()); int tmp = 10; int *ptr2 = &tmp; printf("%p, %d\n", ptr2, tmp); return 0; }
运行结果:
$ ./a.out
0x7ffc5e2c6274, 5
0x7ffc5e2c6294, 10
很明显, 在return_sth()返回之后, *ptr是未定义的, 那么ptr呢?
仍然存在还是一样是未定义的?
在
中,
return_sth()
返回ptr的值,也就是一个地址,虽然与int不匹配,但编译器只会发出警告,但实际上还是一个地址,所以*return_sth()
就是对这个地址解引用,当然也就是5
了,不过你这程序看起来实在没什么意思