我想问你如何在C++中重新分配一个struct
数组?重新分配一个结构数组
在C中有realloc
这是相当不错的,但不建议在C++中使用它。也许你们中的一些人会告诉我,我不应该使用struct
阵列?
那么,在这个任务我们不能使用任何STL容器,所以struct
是唯一的选择,我想。这是为实践的问题与分配,重新分配内存和其他东西...
在下面的示例中,我写了一个代码,我将如何使用malloc
和realloc
在C中执行它。你能给我一个建议如何在C++中做到这一点。
谢谢。
class CCompany
{
public:
CCompany();
bool NewAccount(const char * accountID, int initialBalance);
struct ACCOUNT
{
char *accID;
int initialBalance;
...
};
ACCOUNT* accounts ;
...
...
private:
int ReallocationStep = 100;
int accountCounter = 1;
int allocatedAccounts = 100;
...
}
CCompany::CCompany()
{
accounts = (ACCOUNT*)malloc(allocatedItems*sizeof(*accounts));
}
bool CCompany::NewAccount(const char * accountID, int initialBalance)
{
// Firstly I check if there is already an account in the array of struct. If so, return false.
...
// Account is not there, lets check if there is enough memory allocated.
if (accountCounter == allocatedAccounts)
{
allocatedAccounts += ReallocationStep;
accounts = (ACCOUNT *) realloc(accounts, allocatedAccounts * sizeof(*accounts));
}
// Everything is okay, we can add it to the struct array
ACCOUNT account = makeStruct(accID, initialBalance);
accounts[CounterAccounts] = account;
return true;
}
如果你不想使用'realloc',当'new'可用时,你应该重新考虑使用'malloc'。你应该为更大的尺寸执行'new',复制你已有的内容,然后'delete []'。还要非常小心你的'CCompany'类正在接受字符串的指针并将它们存储为非拥有的(即不需要拷贝)。 –
是的,当然,而不是malloc我会使用新的,但我不确定与realloc。 –
如果在C++中有一个realloc相当于它会杀死它的踪迹中的异常安全。分配新内存后,您希望旧数据仍然存在。分配可能会导致代码处于不一致状态。你应该分配新的块,一旦你知道成功了,然后复制到新块中,然后删除旧块。 –