nichos
nichos

Reputation: 3

Memory allocation Structure with array of structure with array of structure

Im trying to make a cache with C, but I'm having an issue with allocating memory at the last array of a structure

struct block{
 int validBit;
 char *tag;

}    

typedef struct block block_t;

Struct set{
 block_t *blocks;
}

typedef struct set set_t;

Struct cache{
  //Some other variables but not important for this question
  set_t *set;
}

typedef struct cache cache_t;

So I allocate memory for cache like this in a setupCache() function

cache_t *cache = NULL;

cache = malloc(sizeof(cache));
if(cache == NULL){
 fprintf(stdout, "Could not allocate memory for cache!");
}

This works fine, now I allocate memory of an array of struct set with 16 elements

cache->set = malloc(16 * sizeof(cache->set));
//same error check as above here, just left our for precision of question

This also works, now I allocate memory for the block array within the set

for(i = 0; i < 16; i++){
cache->set->blocks = malloc(2 * sizeof(cache->set->blocks));

Again this works, but here the trouble comes

cache->set->blocks[i] = malloc(sizeof(block_t));

This give me an error: incompatible types when assigning to type ‘block_t’ from type ‘void *’

Not really sure what I'm doing wrong, probably something silly.

This is how it should be: The cache holds an array of set struct with 16 elements, each of these set elements should have an array of block struct with 2 elements.

Hope any of you can help me!

Upvotes: 0

Views: 95

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134376

First and foremost, in your code, your memory allocation is wrong. You're providing wrong size altogether for every memory allocation. For example,

cache = malloc(sizeof(cache));

should be

cache = malloc(sizeof(*cache));

and likewise.

After that, cache->set->blocks[i] is of type block_t, not block_t *, so this does not need to be allocated memory dynamically, at all.

Upvotes: 2

Related Questions