【发布时间】:2021-01-31 19:59:39
【问题描述】:
我正在阅读计算机系统:程序员的观点(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 *));
}
【问题讨论】:
-
你没有收到很多关于函数被隐式声明的警告吗?如果没有,请在编译器中启用更多警告。对于 GCC,您可以使用命令行选项
-Wall -Wextra -
那本书真的把
main和show_all_bytes放在了所有其他功能之上吗?试着把它放在它们下面。 -
旁白:3个显示功能中的每一个都可以替换为相同的
show_bytes((byte_pointer) &x, sizeof x);
标签: c floating-point hex