创建一个节点指针数组 [英] Create an array of Node pointers

查看:85
本文介绍了创建一个节点指针数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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 *的数组的有效方法吗?

Is the statement in main a valid way to create an array of 5 Node * 's ?

main语句与<$ c $有什么区别? c> Node ** nodeArray = new Node * [5]; ? Main当前给我一个错误:带括号的type-id |

What is the difference between the statement in main and Node **nodeArray = new Node*[5];? Main currently gives me an error: array bound forbidden after parenthesized type-id|

第二个问题:

如何我将遍历数组并为每个数组做一个新的吗?我曾经使用过数组,也曾经使用过链表,但是将它们组合在一起似乎比我想象的要难。

How would I go through the array and do a new for each one of them? I've worked with arrays and I've worked with linked lists, but putting them together seems trickier than I'd thought.

推荐答案

如果您知道最多需要5个项目,则应该使用静态分配,因为它更快,并且您不必担心会取消分配数组。

If you know that you need maximum of 5 items, you should use static allocation because it's faster and you don't have to worry about deallocating the array.

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

对于动态分配的数组几乎是同一回事,您只需要意识到

For dynamically allocated arrays is pretty much the same thing, you just have to realize the pointer new returns points to the first item in the array.

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;

这篇关于创建一个节点指针数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆