我还不太擅长 C,所以我有一些问题。
我有以下两个结构:
typedef struct line_elems line;
typedef struct cache_handler *cache;
struct line_elems { // we don't care about valid/block bits in our simulator
int tag;
int freq; // for LRU principle
};
struct cache_handler {
int hit;
int miss;
int evict;
line **lines; // 2d array for sets
};
通过以下方式初始化缓存:
cache make_cache(int s, int E) {
int i;
cache new = malloc(sizeof(struct cache_handler));
new->hit = 0;
new->miss = 0;
new->evict = 0;
line **new_line = malloc((1 << s) * sizeof(*new_line));
for(i = 0; i < (1 << s); i++)
new_line[i] = malloc(E * sizeof(struct line_elems));
new->lines = new_line;
return new;
}
现在,我想创建一个系统来搜索二维数组中的单行:
int search_lines(line *lines, int E, int tag, int frequency) {
int i;
for(i = 0; i < E; i++) {
//continue here
}
}
我对到底应该在 search_lines 函数中输入什么内容感到有点困惑。
如果我输入: search_lines(cache->lines[0], E=5, tag=5,Frequency=5)
它会达到我的预期吗?也就是说,它会搜索二维数组中的一行吗?我觉得 cache->lines[0]
与 (line*)
不一样。
cache->lines
和 cache->lines[0]
之间有什么区别?这让我很困惑,因为 ->
运算符是否隐式执行一级取消引用?
谢谢。
最佳答案
“cache->lines 和 cache->lines[0] 之间有什么区别?”
cache->lines
是 struct line_elems**
这是你的二维数组。实际上它是指向二维数组第一个元素的指针。使用运算符 ->
是因为 cache
是 cache_handler*
= 您正在使用它访问 struct cache_handler
的成员。
cache->lines[0]
是 struct line_elems*
,它是索引 0 处的一维数组 = 它也是指向二维数组第一个元素的指针。
请注意,释放此内存的顺序应与分配的顺序相反:
line **new_line = malloc((1 << s) * sizeof(*new_line));
for(i = 0; i < (1 << s); i++)
new_line[i] = malloc(E * sizeof(struct line_elems));
首先释放每个 new_line[i]
,然后释放 new_line
本身:
for(i = 0; i < (1 << s); i++)
free(new_line[i]);
free(new_line);
关于c - C 中的二维数组结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9468965/