以
template<typename Key, typename Value>
struct Node {};
为例,试创建有n个Node类型的node的数组。
方法一(nodes[i]为指针):
struct Node<int, int> *nodes[n];
for (size_t i = 0; i < n; i++)
nodes[i] = (struct Node<int, int>*)malloc(sizeof(struct Node<int, int>) * n);
使用
for (size_t i = 0; i < n; i++) {
std::free(nodes[i]);
}
释放nodes的内存。
方法二(nodes[i]为指针):
struct Node<int, int> **nodes = (struct Node<int, int>**)malloc(sizeof(struct Node<int, int>*) * n);
for (size_t i = 0; i < n; i++)
nodes[i] = (struct Node<int, int>*)malloc(sizeof(struct Node<int, int>));
使用
for (size_t i = 0; i < n; i++) {
std::free(nodes[i]);
}
std::free(nodes);
释放nodes的内存。
方法三(nodes[i]为结构体struct):
struct Node<int, int> *nodes = (struct Node<int, int>*)std::malloc(sizeof(struct Node<int, int>) * n);
使用
std::free(nodes);
释放nodes的内存。如果将nodes插入到类中,注意应考虑类的析构函数。
错误方法:
struct Node<int, int> (*nodes)[n] = (struct Node<int, int>(*)[n])std::malloc(sizeof(struct Node<int, int>) * n);
(参考How to dynamically allocate a 2D array in C?及malloc申请二维数组的四种方法)