Home > Software engineering >  C reach class/structure field
C reach class/structure field

Time:10-15

I'm challenging myself to create my own custom integer array by making a class and structure with some functions. When I run the program I don't get an error, but the data of the index isn't being set, and I don't understand why.

Array class file

#include "IntArray.hpp"
using namespace std;

struct IntArrayIndex {
public:
    IntArrayIndex* next = NULL;
    int data;
    
    IntArrayIndex(int Data) {
        this->data = Data;
    }
    IntArrayIndex() {
        this->data = 0;
    }
};

class IntArray {
public:
    IntArrayIndex head = *(new IntArrayIndex());
    int length;
    
    IntArray() {
        this->length = 1;
        this->head = *(new IntArrayIndex());
    }

    int getIndex(int index) {
        if (index >= length) {
            throw invalid_argument("Index out of range. Returned -1");
        }
        
        IntArrayIndex current = head;
        if (index > 0) {
            current = *current.next;
            getIndex(--index);
        }
        return current.data;
    }
    
    void setIndex(int index, int data) {
        IntArrayIndex current = head;
        if (index > 0) {
            if (current.next == NULL) {
                current.next = new IntArrayIndex();
                length  ;
            }
            current = *current.next;
            setIndex(--index, data);
        }
        current.data = data;
    }
};

Main file

#include <iostream>
#include "IntArray.cpp"

int main(int argc, const char * argv[]) {
    IntArray* l = new IntArray();
    l->setIndex(0, 1);
    std::cout << l->getIndex(0);
}

OUTPUT: 0 Program ended with exit code: 0

CodePudding user response:

Changing the pointers in setIndex ended up fixing the problem:

void setIndex(int index, int data) {
        IntArrayIndex* current = &head;
        if (index > 0) {
            if (current->next == NULL) {
                current->next = new IntArrayIndex();
                length  ;
            }
            current = current->next;
            setIndex(--index, data);
        }
        current->data = data;
    }

CodePudding user response:

In setIndex you are copying head into the local current and then modifying that just before it goes out of scope, taking the data you set with it. Then in getIndex you are creating a different local current that copies the original head, which was left unmodified in setIndex.

update: Right, the change you made in your post below would indeed solve the problem.

  •  Tags:  
  • c
  • Related