返回索引中的细分错误

时间:2020-01-28 18:29:16

标签: c

int* twoSum(int* nums, int numsSize, int target, int* returnSize){

    int i = 0, j = 0;

    for(i=0; i < numsSize; i++)
    {
        for(j = i+1; j < numsSize; j++)
        {
            if(nums[j] == target - nums[i])
            {
                int *index = (int *)malloc(sizeof(int) * 2);
                index[0] = i;
                index[1] = j;
                return index;
            }
        }
    }
    return NULL;
}

我正在为以下代码编写

给出nums = [2, 7, 11, 15]target = 9

由于nums[0] + nums[1] = 2 + 7 = 9, 返回[0, 1]

我尝试调试代码,i和j值分别为0和1。但是现在我在返回索引时遇到了问题。它显示为分段错误。任何人都可以更正上面的代码吗?

2 个答案:

答案 0 :(得分:1)

类似codeforce或类似的平台问题。发生分段错误是因为尚未设置调用者传递的returnSize,而释放返回数组所需的设置却与此相同。因此解决方案是将returnSize设置为2。

答案 1 :(得分:0)

#include <stdio.h>
#include <stdlib.h>
int* twoSum(int* nums, int numsSize, int target, int* returnSize)
{
    int i = 0, j = 0;
    for(i=0; i < numsSize; i++)
    {
        for(j = i+1; j < numsSize; j++)
        {
            printf("i=%d j=%d \n",i,j);
            if(nums[j] == target - nums[i])
            {
                int *index = malloc(sizeof(int) * 2);
                index[0] = i;
                index[1] = j;
                return index;
            }
        }
    }
    return NULL;
}

int main()
{
    int nums[] = {2, 7, 11, 15}; // works
    //int * nums = {2, 7, 11, 15}; //compile OK (some compilers) but Segmentation fault .
    int target = 9;
    int * result = twoSum(nums,4,target,NULL);
    if(result)
        printf("result[0]=%d result[1]=%d" ,result[0] , result[1]);
    return 0;
}