gpt4 book ai didi

c - 结构体静态数组字段的动态内存重新分配

转载 作者:行者123 更新时间:2023-11-30 14:33:33 25 4
gpt4 key购买 nike

考虑以下结构:

// 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];
};

假设以下代码中的 realloc 函数(下面第 5 行)正确地增加了 table 字段的大小,尽管它已定义,是否正确作为静态数组?

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++;
}

最佳答案

不,您不能将任何类型的指针分配给数组。

在此示例中,您将内存分配给传递给 add 的 struct B 指针。这对该结构包含的数组大小没有任何影响。

您尝试执行的操作的实现可能如下所示:

// 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++;
}

关于c - 结构体静态数组字段的动态内存重新分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59241551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com