简体   繁体   English

无法在C中创建包含结构体数组的结构体

[英]Having trouble creating struct containing array of structs in C

Okay I have some typedefs like: 好吧,我有一些typedef,例如:

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? pt.entry不是指针数组吗? 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? 或者更好的方法是,创建包含128个结构体PT_ENTRY的结构体PT的最好,最快的方法是什么?

It's because the entries in the entry array are not pointers. 这是因为entry数组中的entry不是指针。 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 & : 如果在某个时候需要传递单个PT_ENTRY作为指针,则可以使用地址运算符&

some_function(&pt.entry[some_index]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM