Search code examples
cstructdynamic-memory-allocationrealloc

Dynamic memory reallocation for a static array field of a structure


Consider the following structures:

// A simple structure to hold some information 
struct A {
    unsigned long id; 
    char title[100]; 
};

// A simple database for storing records of B
struct B {
    unsigned int tableSize; // Total available space in the 'table' field (initially, set to 5)
    unsigned int entriesUsed; // Number of used entries of the 'table' field
    struct A table[5]; 
};

Is it correct to assume that the realloc function (line 5 below) in the following code increases the size of the table field correctly despite the fact that it is defined as a static array?

void add(struct B* db, struct A* newEntry)
{
    if (db->entriesUsed >= db->tableSize) {
        // Does the following line increase the size of 'table' correctly?
        db = (struct B*)realloc(db, sizeof(db) + 5*sizeof(struct A));
        db->rowsTotal += 5;
    }

    db->table[db->entriesUsed].id = newEntry->id;
    memcpy(db->table[db->entriesUsed].title, table->title, sizeof(newEntry->title));

    db->entriesUsed++;
}

Solution

  • No, you cannot assign pointers of any sort to arrays.

    In this example you are assigning memory to the struct B pointer that you passed into add. This does nothing to the array sizes contained by that structure.

    An implementation of what you're trying to do might look like this:

    // A simple structure to hold some information 
    struct A {
        unsigned long id; 
        char title[100]; 
    };
    
    // A simple database for storing records of B
    struct B {
        unsigned int tableSize; // Total available space in the 'table' field (initially, set to 5)
        unsigned int entriesUsed; // Number of used entries of the 'table' field
        struct A *table; 
    };
    
    void add(struct B* db, struct A* newEntry)
    {
        if (db->entriesUsed >= db->tableSize) {
            // Add 5 more entries to the table
            db->tableSize += 5
            db->table = realloc(sizeof(struct A) * db->tableSize)
        }
    
        memcpy(&db->table[db->entriesUsed], newEntry, sizeof(struct A));
    
        db->entriesUsed++;
    }