Jacqui
Jacqui

Reputation: 13

How to assign values to struct?

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;

}

Upvotes: 1

Views: 92

Answers (1)

Shaddy
Shaddy

Reputation: 59

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.

Upvotes: 1

Related Questions