c - 结构的静态数组字段的动态内存重新分配
问题描述
考虑以下结构:
// 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++;
}
解决方案
不,您不能将任何类型的指针分配给数组。
在此示例中,您将内存分配给struct B
传递给 add 的指针。这对该结构包含的数组大小没有任何影响。
您尝试执行的操作可能如下所示:
// 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++;
}
推荐阅读
- sql - ORA-01722: 无效编号,查找特定行
- r - 在 Polygon 中创建一个网格并使用 geom_tile 填充它
- android - Android:如何使缩放动画不改变按钮中的文本
- serilog - Serilog 可以解构传递给 BeginScope 的复杂对象吗?
- html - 当我添加填充时,div 离开容器
- python - 为什么我得到这个返回值?
- c# - 如何在 WCF Rest Service 中传递多个参数:C# 中的字符串和流
- c# - 比较 ASP.Net Core 中的两个模型以检测无循环的变化
- html - gojs示例“productionProcess”中的浅蓝框如何去掉?
- javascript - 动态启用/禁用树枝中的提交按钮