0

I have got a struct:

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

I want to setup an array of struct line* with the name set.

That is to say I want to initialize L set[];, and then I want to declare an array of the set L* cache[].

So in a function cache_new(int numSets, int numLines) I want to initialize them using malloc(), how can I do that? New to C, any help will be appreciated.

1
  • 1
    use calloc(numSets, sizeof(line)) Commented Jun 19, 2014 at 10:59

2 Answers 2

1

If your array is declared with [] then you cannot dynamically allocate it. The [] mean the array will be automatically or statically allocated.

To dynamically allocate some structs that are zeroed, you should do:

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

With dynamic allocation, the array itself does not have a name, however using the pointer set which points to its first element, you can still access all the array members.

I'm not exactly clear on what you are asking about cache, but perhaps it is supposed to be:

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]);

Please don't use pointer typedefs, they make the code hard to read. You can typedef struct line Line; if you want. And it doesn't really matter whether you do calloc(N, size) or malloc(N * size).

Then you can access those arrays using [] notation, e.g. cache[3][5].tag = 7;

Sign up to request clarification or add additional context in comments.

2 Comments

Quite a few calloc() implementations check for integer overflow.
@ninjalj yeah, and it can be faster too on some operating systems
0
L cache;
var = (L)malloc(n * sizeof(cache[0]));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.