leetcode 报错 load of null pointer of type ‘int‘ (

    科技2022-07-12  112

    题目

    https://leetcode-cn.com/problems/two-sum/

    暴力解法

    /** * Note: The returned array must be malloced, assume caller calls free(). */ int* twoSum(int* nums, int numsSize, int target, int* returnSize){ int a; int b; static int ans[2]; int *ansx; int *result = (int *)malloc(sizeof(int) * 2); ansx=ans; for(int i=0;i<numsSize-1;i++){ for(int j=i+1;j<numsSize;j++){ if (nums[i]+nums[j] == target && i!=j ){ ans[0]=i; ans[1] =j; *returnSize = 2; return ans; } } } return ans; }

    报错

    原因

    返回的数据为局部的变量

    因此将返回的数值变成静态变量就可行了。 因为函数返回的是指针地址指向函数内的局部变量数组,在函数退出时,数组的存储空间会被销毁,此时去访问该地址就会出现这个错误。

    修改方法一般有3种:

    1)返回的指针提前分配空间

    2)用static修饰变量

    3)使用全局变量

    参考:https://www.cnblogs.com/zygote/p/13192620.html

    Processed: 0.008, SQL: 8