我正在阅读《计算机系统:程序员的观点》(Bryant和O'Hallaron)。在第2章图2.4中,它显示了以下代码
#include <stdio.h>
typedef unsigned char *byte_pointer;
void show_bytes(byte_pointer start, int 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.4打印程序对象字节表示的代码。此代码使用强制转换来规避类型系统。可以为其他数据类型轻松定义类似的功能
然后使用以下方法
void test_show_bytes(int val) {
int ival = val;
float fval = (float) ival;
int *pval = &ival;
show_int(ival);
show_float(fval);
show_pointer(pval);
}
根据这本书,如果值是12345,则此测试方法应在linux 64上打印以下内容
39 30 00 00
00 e4 40 46
b8 11 e5 ff ff 7f 00 00
但是,当我运行代码时,得到以下结果
39 30 00 00
00 00 00 00
d8 d6 54 c3 fd 7f 00 00
我使用的是gcc版本7.5.0(Ubuntu 7.5.0-3ubuntu1〜18.04),我正在运行的代码基于我对C还是很陌生的书中的示例得出,为什么我的结果有所不同?
#include <stdio.h>
typedef unsigned char *byte_pointer;
nt main(){
int val = 12345;
test_show_bytes(val);
}
void test_show_bytes(int val) {
int ival = val;
float fval = (float) ival;
int *pval = &ival;
show_int(ival);
show_float(fval);
show_pointer(pval);
}
void show_bytes(byte_pointer start, int 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 *));
}
show_float(fval);
在看到功能定义之前使用show_float(float x)
-否。不要那样做 使所有编译器警告更加有效。
编译器猜测的定义为show_float(double x)
,因此在show_float(fval);
调用过程中传递了错误的信息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句