先看一段代码:(摘自《深入理解计算机系统》)
#include <stdio.h> #include<stdlib.h> typedef unsigned char *byte_pointer; void show_bytes(byte_pointer start, size_t len) { int i; for (i = 0; i < len;i++) { printf(" %.2x", start[i]); } printf("\n"); } void show_int(int x) { show_bytes((byte_pointer)&x, sizeof(int)); } void show_float(float x) { show_bytes((byte_pointer)&x, sizeof(float)); } void show_pointer(void *x) { show_bytes((byte_pointer)&x, sizeof(void *)); } //课后题2.5 int main() { int val = 0x87654321; byte_pointer valp = (byte_pointer) &val; show_bytes(valp, 1); show_bytes(valp, 2); show_bytes(valp, 3); system("pause"); }
其中就涉及到(byte_pointer) &val,往上看函数定义我们可以看到,这里其实已经把&val强制转换成指针类型了,&val这个指针变量和我们之前学习Int *p中指针变量p不一样,&val是一个字节序列,而p指向它存放的地址的对象。所以在(byte_pointer) &val这个指针,会被看成是最低字节来开始使用
附上运行结果:

此时运行的就是从最低位,倒数第二位,倒数第三位的数据。
此时我们就很好理解(int*)&a是什么意思了:取a的地址,将a的地址转换成int类型的指针变量,指向的a地址的最低位开始的数据。
2532

被折叠的 条评论
为什么被折叠?



