我有一个展开的链接列表
class UnrolledLinkedList {
Node* head;
Node* tail;
int size; //num of elements in List
int numOfNodes;
int nodeSize;
}
具有这样的Node
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("NULL\n");
}
在主要情况下,它在第delete[] arr;
行发现了错误的HEAP CORRUPTION DETECTED
请帮我!
预先谢谢你!
答案 0 :(得分:10)
以下陈述与您的想法不符:
int* arr = new int(size);
它将创建一个单独的int
,其值是size
。
您的代码肯定可以更好地配合:
int* arr = new int[size];