Но когда я пытаюсь распечатать значения с помощью функции printList(), адреса памяти изменяются, и я больше не могу получить доступ к сохраненному ранее значению.
Код, о котором идет речь:
Код: Выделить всё
#include
#include
class Node{
private:
// Attributes
int value;
Node* nextNode;
public:
// Empty Constructor
Node(){
value = 0;
}
// Value-and-address Constructor
Node(int localValue, Node* localAddress){
value = localValue;
nextNode = localAddress;
}
// Value Setter
void setValue(int localValue){
value = localValue;
}
// Address Setter
void setAddress(Node* localAddress){
nextNode = localAddress;
}
// Value Getter
int getValue(){
return value;
}
// Next Node Address Getter
Node* getNextNode(){
return nextNode;
}
};
class linkedList{
private:
Node* firstNode;
Node* lastNode;
int sizeOfNode = sizeof(Node);
int lengthOfList = 0;
int iter;
Node* container = (Node*)malloc(sizeof(Node)); // Container for last node
public:
// Constructor
linkedList(int sizeOfList, int* localArray){
// Creation of first Node
firstNode = (Node*)malloc(sizeOfNode);
*firstNode = Node(localArray[0], container);
Node* previousNode = previousNode; // Current Node
lengthOfList ++;
for(int i = 1; i < sizeOfList-1; i++){
iter = i;
Node* currentNode = (Node*)malloc(sizeOfNode);
printf("\n Next Node Location: %p", currentNode);
(*previousNode).setAddress(currentNode);
printf("\n Current Node Location: %p", (*previousNode).getNextNode());
*currentNode = Node(localArray[i], container);
previousNode = currentNode;
lengthOfList ++;
}
// Creation of last Node
iter++;
lastNode = (Node*)malloc(sizeOfNode);
*lastNode = Node(localArray[iter], container);
lengthOfList ++;
}
void printList(){
// First Print
Node* currentNode = firstNode;
for(int i = 0; i < lengthOfList; i++){
printf("\n%d: %d\n", i, (*currentNode).getValue());
printf("Next Node Location: %p\n", (*currentNode).getNextNode());
currentNode = (*currentNode).getNextNode();
}
}
};
int main(){
int passedArray[] = {1, 2, 3, 4};
int sizeOfPassedArray = sizeof(passedArray)/sizeof(int);
linkedList list1 = linkedList(sizeOfPassedArray, passedArray);
list1.printList();
}
Код: Выделить всё
Next Node Location: 00000261A1E6F940
Current Node Location: 00000261A1E6F940
Next Node Location: 00000261A1E6F700
Current Node Location: 00000261A1E6F700
0: 1
Next Node Location: 00000261A1E6F780
1: 0
Next Node Location: 0000000000000000
- Вывод печатает другой адрес.
Я по-прежнему могу нормально получить доступ к первому узлу.
Отладчик показывает ошибку сегментации в возвращаемое значение в функции getValue(), если это актуально, но это только со второй итерации цикла printList() и далее.
Подробнее здесь: https://stackoverflow.com/questions/788 ... pon-exitin