0

These are sections of C code used to implement a hashmap using open-addressing. I don't understand what the while loop in the insert function is checking and the if statement in the twoSum Function is checking for.

Does the while loop condition check if the value is in the array or if the value isn't null. Does the if statement check if the value is not 0? I don't understand.

I always thought something like this would work like a while(1) loop that needs to manually break.

I want to know what the conditions of the loops guard statement are I understand the body.

void insert(int *keys, int *values, int key, int value) {
    int index = hash(key);
    while (values[index]) { // What does this check for?
        index = (index + 1) % SIZE;
    }
    keys[index] = key;
    values[index] = value;
}
int* twoSum(int* nums, int numsSize, int target) {
    int keys[SIZE];
    int values[SIZE] = {0};
    for (int i = 0; i < numsSize; i++) {
        int complements = target - nums[i];
        int value = search(keys, values, complements);
        if (value) { // What does this line check for?
            int *indices = (int *) malloc(sizeof(int) * 2);
            indices[0] = value - 1;
            indices[1] = i;
            return indices;
        }
        insert(keys, values, nums[i], i + 1);
    }
    return NULL;
}

1 Answers1

0

We can only guess.

It looks like insert expects pointers to arrays that always have a final element of value zero, that the designer of the function has chosen that convention to signify "end of the array".

And it looks like search returns zero when the search failed.

However, either could instead be a bug (I'm suspicious because this design prohibits zero ever being treated as a "real"/valid value), and both are arguably bad design — in the former case, why not pass the array size as an argument instead? In the latter case, why not return bool and give the result (if successful) as an "out argument", like other C APIs?

Ultimately, we cannot magically know the preconditions of a function, so you will have to ask the person who wrote it.

This is why code should have explanatory comments.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055