krb686
krb686

Reputation: 1796

Having trouble creating struct containing array of structs in C

Okay I have some typedefs like:

typedef struct {
    int validBit
    int pageNumber
} PT_ENTRY;

typedef struct {
    PT_ENTRY entry[128];
} PT;

Later on in the code, I attempt:

PT pt = {};

int i;
for(i=0;i<128;i++){
    pt.entry[i] = malloc(sizeof(PT_ENTRY));
}

This gives me the error:

Incompatible types in assignment.

So I'm confused, because I thought I did this exact same thing yesterday and it worked, then I changed my code but decided to change it back.

Isn't pt.entry an array of pointers? What am I missing here?

Or better yet, what's the best and fastest way to create this struct PT containing an array of 128 structs, PT_ENTRY?

Upvotes: 0

Views: 2034

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

It's because the entries in the entry array are not pointers. It's an array of actual structures, not pointers to structures.

If you wanted an array of pointers, you needed to declare the array as

PT_ENTRY *entry[128];

But you need to to think about if you really need an array of pointers? Most likely you don't need it, and should let it be like it is. So then there is no memory to allocate, no memory to free, no worries about memory leaks or invalid pointers. If, at some point, you need to pass a single PT_ENTRY as a pointer then you can use the address-of operator &:

some_function(&pt.entry[some_index]);

Upvotes: 6

Related Questions