如何将一个int数组分配给链表结构?

时间:2019-03-11 16:32:09

标签: c++

您好,我是c ++的初学者,无法解决此问题。我有一个节点链表,该节点包含int数组的数据和一个指向下一个节点的指针。

struct node {
   unsigned int numbers[6];
   node* next;
};

我也有一个课程:

private:
   ticket* ticketListHead;
   ticket* ticketListTail;

并使用公共方法:

public:
    void newNode() {

       int arr[6];

       for(int i = 0; i < 6; ++i) {
           arr[i] = ( std::rand() % 49 ) + 1;
       }

       node *temp = new node;
       temp->numbers=arr;
       temp->next=NULL;
}

我认为问题在于temp->numbers=arr行,因为我相信数组不能像C ++中那样分配。在这种情况下,我不确定如何解决该问题,并且我尝试过在线查找。一些帮助,将不胜感激!

2 个答案:

答案 0 :(得分:0)

欢迎使用C ++,您迈出了进入更明亮世界的第一步!您需要研究的是C ++容器类,它们使您摆脱了自行管理内存的业务。与您的代码最接近的是std :: list和std :: vector。我会忽略随机数播种,这是一个复杂的话题,在其他地方可以更好地讨论。

function printDate(){
    const d = new Date(document.getElementById("date").value); // will treat input as UTC

    // will output as UTC in ISO 8601 format
    alert(d.toISOString());

    // will output as UTC in an implementation dependent format
    alert(d.toGMTString());

    // will output as UTC in a locale specific format
    alert(d.toLocaleString(undefined, {timeZone: 'UTC'}));
}

答案 1 :(得分:-1)

// Change node struct to this 
struct node{
unsigned int *numbers;
node* next;
};

/*
Remember that normal arrays are 
implemented through pointers. So you 
can use a pointer named numbers in 
your node struct and it would behave 
as an array.
*/

// Change newNode() to this 
void newNode() {
int * arr = new int[6]; //Dynamic memory allocation
for(int i = 0; i < 6; ++i) 
{ 
arr[i] = ( std::rand() % 49 ) + 1; 
}
node *temp = new node; 
temp->numbers = arr; 
temp->next = NULL;
}

你明白了吗?