c - how to malloc array of structs using malloc -
i have got struct:
struct line{ bool isvalid; int tag; int block; }; typedef struct line* l; i want setup array of struct line* name set.
that want initialize l set[];, , want declare array of set l* cache[].
so in function cache_new(int numsets, int numlines) want initialize them using malloc(), how can that? new c, help appreciated.
if array declared [] cannot dynamically allocate it. [] mean array automatically or statically allocated.
to dynamically allocate structs zeroed, should do:
struct line *set = calloc(num_lines, sizeof *set); with dynamic allocation, array not have name, using pointer set points first element, can still access array members.
i'm not clear on asking cache, perhaps supposed be:
struct line **cache = calloc(num_sets, sizeof *cache); (size_t = 0; < num_sets; ++i) cache[i] = calloc(num_lines, sizeof *cache[i]); please don't utilize pointer typedefs, create code hard read. can typedef struct line line; if want. , doesn't matter whether calloc(n, size) or malloc(n * size).
then can access arrays using [] notation, e.g. cache[3][5].tag = 7;
c arrays struct
No comments:
Post a Comment