问题描述
我正在尝试实现一个单元缓存结构并使用 calloc
方法(动态分配)为其提供内存空间。我使用类型定义的 cache_unit
作为指针的类型来接收来自 calloc
的转换返回类型。通常在 calloc
之后,分配区域中的所有位都应为 0。但是我的输出类似于随机数而不是 0,并且有两条警告消息。
这是我的代码:
#include<stdio.h>
#include<stdlib.h>
#include <cstdint>
int main() {
typedef struct {
bool enabled;
uint8_t block[10];
int access_time;
} cache_unit;
cache_unit* cache = (cache_unit*) calloc(2,sizeof(cache_unit));
printf("%x ",*cache);
return 0;
}
解决方法
对于 printf("%x ",*cache);
,"%x"
需要匹配的 unsigned
,而不是 cache_unit
。
试试
printf("%d\n",cache->access_time);