Background context: I was doing leetcode twoSum and trying to understand one of the solutions. So, I decided to implement the solutions in the code block and use the debugger.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 50000
int hash(int key);
void insert(int *keys, int *values, int key, int value);
int search(int *keys, int *values, int key);
int* twoSum(int* nums, int numsSize, int target, int* returnSize);
int main()
{
int ar[4]={2,7,11,15};
int *ans;
int *returnSize;
ans=malloc(2*sizeof(int));
ans=twoSum(ar,4,9,returnSize);
printf("d d ",ans[0],ans[1]);
free(ans);
return 0;
}
int hash(int key) {
int r = key % SIZE;
return r < 0 ? r + SIZE : r;
}
void insert(int *keys, int *values, int key, int value) {
int index = hash(key);
while (values[index]) {
index = (index + 1) % SIZE;
}
keys[index] = key;
values[index] = value;
}
int search(int *keys, int *values, int key) {
int index = hash(key);
while (values[index]) {
if (keys[index] == key) {
return values[index];
}
index = (index + 1) % SIZE;
}
return 0;
}
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
*returnSize = 2;
int keys[SIZE]; //new array
int values[SIZE] = {0}; //new array
for (int i = 0; i < numsSize; i++) {
int complements = target - nums[i];
// check for complements in the hash table
int value = search(keys, values, complements);
if (value) {
//return an array
int *indices = (int *) malloc(sizeof(int) * 2);
indices[0] = value - 1;
indices[1] = i;
return indices;
}
//if not insert the current values
insert(keys, values, nums[i], i +1);
}
return NULL;
}
When I use the debugger, the error SEGMENTATION fault appears at line *returnSize=2? What is the problem?
I was trying to understand why i+1 in insert(keys, values, nums[i], i +1) instead of i?