Search code examples
cstructtypedef

C structs and typedefs


I am not sure why this does not work. I am a bit confused about the typedef's

typedef struct cache_line {
    int valid;
    int tag;
    int usage;
} cache_line_t;

typedef cache_line_t* cache_set_t;

typedef cache_set_t* cache_t;

void init() {
  S = 2 << (s-1);
  B = 2 << (b-1);

  cache = malloc(sizeof(cache_set_t*) * S);
  for(int i = 0; i < S; i++) {
    cache[i] = malloc(sizeof(cache_line_t*) * E);
    for(int j = 0; j < E; j++) {
      cache[i][j]->valid = 0;
      cache[i][j]->tag = 0;
      cache[i][j]->usage = 0;
    }
  }
}

Compiling gives an error with the ->'s

s, b, S, B, and E are ints. cache is defined above as a cache_t. I am trying to make an array of S sets which are arrays of E lines.

Any help is greatly appreciated


Solution

  • Change cache = malloc(sizeof(cache_set_t*) * S); to cache = malloc(sizeof *cache * S);, because you need space for S objects that cache points to, not S objects of the type that cache is.

    Change cache[i] = malloc(sizeof(cache_line_t*) * E); to cache[i] = malloc(sizeof *cache[i] * E);, for the same reason.

    Change:

      cache[i][j]->valid = 0;
      cache[i][j]->tag = 0;
      cache[i][j]->usage = 0;
    

    to:

      cache[i][j].valid = 0;
      cache[i][j].tag = 0;
      cache[i][j].usage = 0;
    

    because cache[i][j] is a structure, not a pointer to a structure.