I am writing an Insert function for a hash table and I need to create a key-value pair(struct Item) in that function. I found that if I create it on the stack e.g. Item item(key, value);
, then every time when I call Insert, different key-value pair will be created in the same location on the stack. This won't happen if I use heap-allocation memory. Why they are at the same location on the stack?
Here is my sample code:
void Insert (int key, int value) {
int hash_value = Hash(key);
if (hash_value >= table.size() || hash_value < 0) {
throw std::out_of_range("Cannot insert.");
} else {
Item *item = new Item(key, value); // This will work
// Item item2(key, value); This does not work
if (!table[hash_value]) { // there is not item in this cell
Cell *c = new Cell(0, item); // Cell *c = new Cell(0, &item2)
table[hash_value] = c;
} else { // try next one, if occupied, the one after ...
int index = hash_value + 1;
while (table[index]) {
++index;
if (index == table.size()) {
index = 0;
} else if (index == hash_value) {
throw std::out_of_range("Opps! The table is full! Cannot insert!");
}
}
Cell *c = new Cell(0, item); // Cell *c = new Cell(0, &item2)
table[index] = c;
}
}
}
Item2 is stack allocated and the way I used it was in the comments.