我有一个展开链表
class UnrolledLinkedList {
Node* head;
Node* tail;
int size; //num of elements in List
int numOfNodes;
int nodeSize;
}
具有类似的节点
class Node {
private:
int maxElements;
public:
int numElements; // number of elements in this node, up to maxElements
int* elements; // an array of numElements elements,
Node *next; // reference to the next node in the list
Node *prev; // reference to the previous node in the list
}
我想把元素放在一个数组中。这是我的乐趣:
int* UnrolledLinkedList::toArray() {
int* arr = new int(size);
Node* pTemp = head;
int i = 0, j = 0, temp = 0;
while (pTemp) {
i = 0;
while (i < pTemp->numElements) {
if (i != 0) j++;
*(arr + j) = pTemp->elements[i];
i++;
}
pTemp = pTemp->next;
j++;
}
return arr;
}
当我打电话给
int* arr = list->toArray();
int n = list->getSize();
printf("The list after converted to array:n");
if (n > 0) {
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("n");
delete[] arr;
}
else {
printf("NULLn");
}
总的来说,它在delete[] arr;
行发现了一个错误HEAP CORRUPTION DETECTED请帮帮我!提前谢谢!
以下语句并不像您想象的那样起作用:
int* arr = new int(size);
它创建一个int
,以值size
初始化。
你的代码肯定会更好地使用:
int* arr = new int[size];