C 将整数指针传递到函数时出现分段错误

C 将整数指针传递到函数时出现分段错误,c,C,背景背景: 我正在做并且试图理解其中一个解决方案。因此,我决定在代码块中实现解决方案并使用调试器 #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* twoSu

背景背景: 我正在做并且试图理解其中一个解决方案。因此,我决定在代码块中实现解决方案并使用调试器

#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;
}    
使用调试器时,错误分段错误出现在第*returnSize=2行? 有什么问题

我试图理解为什么插入键、值、nums[I]中的I+1、I+1而不是I

您需要先初始化returnSize,然后才能取消引用它。您得到UB是因为您取消引用了未初始化的指针。但我怀疑您真正想要的是将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;
}
请注意,main中的returnSize现在是int而不是int*类型。它的地址被传递给函数twoSum。区别在于传递给函数的指针指向现有变量