mercredi 15 avril 2020

C++ Struct attributes can change within function, but remain unchanged outside scope of function

I'm working on a self imposed challenge which involves implementing a linked list and an append function for it, which is giving me issues seemingly related to variable scope.

The append function loops through each link element until it reads a NULL value and then changes the data value associated with that link to the function input. The test outputs within the function seem to show it is working as intended, but when performing the same test outside the function, even after it is called gives a different output.

template <class T>
struct atom{
    T data;
    atom<T>* link = NULL;
};

template <class T>
void append_LL(atom<T> first, T input_data){

    atom<T>* current_node = &first;

    atom<T>* next_node = current_node->link;

    int i = 0;
    while (i < 4 && next_node != NULL) {
        current_node = next_node;
        next_node = next_node->link;
        i ++;
    }
    current_node->data = input_data;
    current_node->link = (atom<T>*)malloc(sizeof(atom<T>));
    cout << "leaving node as: " << current_node->data << endl; //outputs 5
    cout << "input nodes data: " << first.data << endl;        //outputs 5
}
int main() {

    int dd = 5;
    atom<int> linked_list;
    linked_list.data = 999;

    append_LL(linked_list, dd);

    cout << linked_list.data << endl; //outputs 999
}

Aucun commentaire:

Enregistrer un commentaire