c++ - 创建一个节点指针数组

标签 c++ arrays pointers

  struct Node {
      int data;        // The data being stored at the node
      Node *next;     // Pointer to the next node
      };

int main()
{
         Node **nodeArray = new (Node*)[5];
}

第一个问题:

main 中的语句是否是创建包含 5 个 Node * 的数组的有效方法?

main 和 Node **nodeArray = new Node*[5]; 中的语句有什么区别? Main 目前给我一个错误:在带括号的 type-id 之后禁止数组绑定(bind) |

第二个问题:

我将如何遍历数组并为它们中的每一个做一个新的?我使用过数组和链表,但将它们放在一起似乎比我想象的要棘手。

最佳答案

如果您知道最多需要 5 个项目,您应该使用静态分配,因为它速度更快,而且您不必担心重新分配数组。

Node* array[SOME_CONST];
for (int i=0; i < SOME_CONST; i++)
{   
   array[i] = new Node()
   cout<<array[i];
}

对于动态分配的数组来说几乎是一回事,你只需要意识到指针 new 返回指向数组中的第一项。

Node** array = new Node*[some_num];
for (int i=0; i < some_num; i++)
{
   array[i] = new Node();
}

不要忘记正确释放:

for (int i=0; i < some_num; i++)
{
   delete array[i];
}
delete[] array;

关于c++ - 创建一个节点指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26373694/

相关文章:

c++ - 检查 IX 或 IV 后是否跟另一个字符

c++ - 非重复随机数发生器

c++ - QSqlRecord 在查询中将具有默认值的列设置为空

c++ - Eclipse CDT 中未识别 Linux CLOCK_PROCESS_CPUTIME_ID

c - C 中带索引的指针和数组

java - 断言 double 组精确相等

javascript - 有效评估 JavaScript 对象是否包含字符串

python - 值错误 : all the input arrays must have same number of dimensions

c - 函数指针不兼容的指针类型 void (*)(void *) from void (my_type *)

对 *char 的字符分配不起作用