c - C 中的二维数组结构

标签 c pointers struct

我还不太擅长 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->linescache->lines[0] 之间有什么区别?这让我很困惑,因为 -> 运算符是否隐式执行一级取消引用?

谢谢。

最佳答案

“cache->lines 和 cache->lines[0] 之间有什么区别?”

cache->linesstruct line_elems** 这是你的二维数组。实际上它是指向二维数组第一个元素的指针。使用运算符 -> 是因为 cachecache_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/

相关文章:

c++ - g++ 空函数删除是否递归工作?

c - 如何区分一个子进程与其他子进程

c - 在 c 或 c++ 中具有负值的子集总和

c++ - 在指针中编码其他信息

c - 贝尔曼福特图算法

c++ - weak_ptr 包含哪些变量?

c - 如何调用传递给另一个函数的任意 C 函数?

C++ 使用 QuickSort 对数组结构进行排序

c - 静态初始化的结构自引用

C 结构体内存存储顺序