1

I have a struct to assign values to it. But my programm crashs it. Hopefully you can help me.

struct HashEntry{
    std::string key;    //the key of the entry
    bool used;          //the value of the entry
    int value;          //marks if the entry was used before

};

HashEntry *initHashList(int N){
     HashEntry* hashList = new HashEntry[N];
    for (int i = 0; i <= N; i++){
        hashList[i].key = " ";
        hashList[i].value = -1;
        hashList[i].used = false;
    }
    for(int i = 0; i <N; i++){
        cout<<hashList[i].value<<endl;
    }
    return hashList;

}
2
  • 2
    i <= N in your first loop should be i < N, or you'll attempt to access hashList[N], which corresponds to the (N+1)th element (which doesn't exist). Commented Jul 21, 2016 at 10:52
  • Change i <= N to i < N as that will cause a crash because you are trying to access an element in your hashList that is out of bounds. Arrays are generally 0 based, so they start at index 0 up to N - 1 in your case. Where are you cleaning up after your hashList memory allocation as I don't see it in this code? Commented Jul 21, 2016 at 10:55

1 Answer 1

1

You iterate through one element too many on creation:

for (int i = 0; i <= N; i++){

Shoule be

for (int i = 0; i < N; i++){

It's because with arrays being 0-based, you can't access the element N of an array of the size N, only N-1, but in return also element 0.

Also, to make the code clearer and less error prone, you could use std::array instead of a pure C style array, or even an std::vector to be able to loop through them range based. You might also rething your use of new which should be avoided in most cases. If you don't really need that, I'd change the function to

std::vector<HashEntry> initHashList(int N) {
    std::vector<HashEntry> hashList(N, { "", false, -1, }); //Creating vector of N elements

    for (const HashEntry& entry : hashList) { //Iterating through the elements
        std::cout << entry.value << std::endl;
    }
    return hashList;
}

I hope this makes it clearer how you can approach such a problem.

This way of creating the vector and looping through it avoids the potential access errors and is easier to read, imo. For more information, search for std::vector, its constructors, and range-based loops.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.