Strange structure confusion

Viewed 64

Consider the following c code:

#define MAX_PROP 16

struct property_setA {
    u32 p1;
    u32 p2;
};

struct property_setB {
    u32 Pg;
};

struct objectA {
    struct property_setA personal_properties [MAX_PROP];
    struct property_setB global_property;
};

Now the task is to create a function allocate_obj which will give some fixed global property (say 32) and initialize the other personal property's memebers (i.e. p1,p2 to 0) I was able to achieve following code

struct objectA* allocate_obj() {
    struct objectA *obj = (struct objectA*)malloc(sizeof(struct objectA);

    // Assign global property
    obj->global_property.Pg = 32;
    // Initialize property_setA fields for this obj


    return obj;
}

Here are my doubts:

  1. What does personal_properties [MAX_PROP] means. I mean is it saying for every objectA, there will be 16 number of property_setA structure will be created or we have to choose the first unused (out of 16) index.

  2. If we have to use the first unused, how to get that number. I was trying following for loop (inside allocate_obj()) but it is giving error.

    u32 i,pd;
    for(i=0;i<MAX_PROP;i++){
     if(obj->personal_properties[i] == NULL){     // This line give error
         pd = i;
         break;
     }
    }
    

So how to get the first unused index?

1 Answers
if(obj->property_setA[i] == NULL){     // This line give error

This line gives an error because once you index the array, you do not have a pointer (struct property_setA*) that you can compare to NULL, you have an actual struct property_setA.

You have two options:

  1. change the declaration of your array to be an array of pointers:
struct objectA {
    struct property_setA* personal_properties [MAX_PROP];
    struct property_setB global_property;
};

// and then be sure to initialize them all to NULL:
struct objectA* allocate_obj() {
    struct objectA *obj = (struct objectA*)malloc(sizeof(struct objectA);

    memset(obj->personal_properties, 0, sizeof(struct property_setA*) * MAX_PROP);
    // Assign global property
    obj->property_setB.Pg = 32;
    // Initialize property_setA fields for this obj

    return obj;
}

Keep in mind in this case you must now malloc and free the underlying objects when setting/deleting them.

  1. Much more simply, add a used counter to your structure and keep track manually of how many properties are used:
struct objectA {
    size_t used_properties;
    struct property_setA personal_properties [MAX_PROP];
    struct property_setB global_property;
};

Initialize it to 0; the next free property is at that index. When you set a property, increment it (ensuring you don't write past MAX_PROP - 1).

Related