gpt4 book ai didi

c - 用于缓存模拟器的 Malloc 两个结构

转载 作者:行者123 更新时间:2023-11-30 14:34:15 25 4
gpt4 key购买 nike

typedef struct {
uint32_t valid_bit;
uint32_t tag;
uint32_t index;
uint32_t data[4];
} Block;

// Final cache structure
typedef struct {
Block* blocks;
} Cache;

Cache myCache;

myCache.blocks = (Block*) malloc(noOfBlocks * sizeof(Block));

for (int i = 0; i < noOfBlocks; i++) {
for (int j = 0; j < 4; j++){
myCache.blocks[i].valid_bit = 0;
myCache.blocks[i].tag = 0;
myCache.blocks[i].index = i;
myCache.blocks[i].data[j] = 0;
}
}

我不确定这是否是应该使用 malloc 的方式。我是否也必须 malloc 我的 data[] 才能稍后访问它?

另外,这是初始化我的缓存的方法吗?

提前致谢!

最佳答案

for 循环中的前三个语句应位于外循环中:

for (int i = 0; i < noOfBlocks; i++) {
myCache.blocks[i].valid_bit = 0;
myCache.blocks[i].tag = 0;
myCache.blocks[i].index = i;
for (int j = 0; j < 4; j++) {
myCache.blocks[i].data[j] = 0;
}
}

另外,请确保在使用完内存后释放内存:

free(myCache.blocks);

除此之外都还好。

Do I have to malloc my data[] too in order to access it later on?

不,数组不是动态分配的。

关于c - 用于缓存模拟器的 Malloc 两个结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59027411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com