0

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?

1 Answer 1

6

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]);
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh, I guess I did delete that little *. Good, that's what I wanted to hear, that I don't need an array of pointers. Thank you!

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.