【发布时间】:2021-02-01 02:30:15
【问题描述】:
我正在尝试模拟一个简单的缓存。我有几个问题。 1) 是否可以使 Line 或 Set 中的数组长度任意。就像通过使用构造函数一样。 2) 运行此代码时出现 Seg Fault,但我不知道为什么。我错误地访问了数组?
提前谢谢你。
#include <stdio.h>
#include <stdlib.h>
struct Line {
unsigned int valid;
unsigned int tag;
}line;
typedef struct Line Line;
struct Set {
Line lines[5];
}set;
typedef struct Set Set;
struct Cache {
Set sets[5];
}cache;
typedef struct Cache Cache;
int main(void) {
Cache *cache = calloc(1,sizeof(Cache));
for(int i=0; i<5; i++){
for(int j=0; i<5; j++){
cache->sets[i].lines[j].valid = 0;
cache->sets[i].lines[j].tag = 0;
}
}
free(cache);
}
【问题讨论】:
-
您的内部循环中有错字:
for (int j = 0; i < 5; j++) {应该是for (int j = 0; j < 5; j++) {。 -
OT:您正在声明名为
line、set和cache的全局变量。我猜你不想要那些。例如,struct Cache的声明应为struct Cache { Set sets[5]; };请注意,最后的cache已删除。 -
当然,在
calloc之后,循环遍历新对象将其设置为0是多余的。
标签: c caching struct segmentation-fault