如何使用malloc malloc结构数组

用户3756003

我有一个结构:

struct line{
  bool isValid;
  int tag;
  int block;
};
typedef struct line* L;

我想设置一个struct line*具有名称集的数组

那就是说我要初始化L set[];,然后要声明集合的数组L* cache[]

因此,在一个函数中,cache_new(int numSets, int numLines)我想使用初始化它们malloc(),我该怎么做?C的新手,任何帮助将不胜感激。

毫米

如果用声明了数组,[]则无法动态分配它。[]指阵列能够自动或静态分配。

要动态分配一些被清零的结构,您应该执行以下操作:

struct line *set = calloc(num_lines, sizeof *set);

使用动态分配,数组本身没有名称,但是使用指向set其第一个元素的指针,您仍然可以访问所有数组成员。

我不清楚您要问什么cache,但也许应该是:

struct line **cache = calloc(num_sets, sizeof *cache);
for (size_t i = 0; i < num_sets; ++i)
    cache[i] = calloc(num_lines, sizeof *cache[i]);

请不要使用指针typedef,它们会使代码难以阅读。您可以typedef struct line Line;根据需要。而且它并没有真正无论你做calloc(N, size)malloc(N * size)

然后,您可以使用[]表示法访问这些数组,例如cache[3][5].tag = 7;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章