力扣报错runtime error: load of null pointer of type ‘int‘解决思路

记录本算法小白刷力扣的这道题遇到的报错

349. 两个数组的交集力扣报错runtime error: load of null pointer of type ‘int‘解决思路https://leetcode.cn/problems/intersection-of-two-arrays/

出现报错的代码 

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){
    int hash[1000]={0};
    int result[1000];//交集是去重的,最多只有1000个数
    for(int i=0;i<nums1Size;i++){//将nums1录入哈希表
        hash[nums1[i]]++;
    }
    int j=0;
    for(int i=0;i<nums2Size;i++){//将nums2与哈希表比对
        if(hash[nums2[i]]!=0){
            result[j]=nums2[i];
            j++;
            hash[nums2[i]]=0;//手动去重
        }
    }
    *returnSize=j;//这个是主函数输出时用的,跟内部计算关系不大
    return result;
}

 报错描述

 Line 207: Char 3: runtime error: load of null pointer of type ‘int’ [__Serializer__.c]

原因分析 

该题需要return一个数组,而在不申请空间(不malloc)的情况下函数内建立的数组是局部变量,无法带回主函数。

解决方法

在函数里malloc需要返回的数组(其实初始代码顶部的note里说的就是这个)。注意建立数组时在中括号里写数组大小跟malloc的效果在这方面是完全不一样的。

这里用于返回的数组是result,所以在建立result数组时要malloc

修改后的代码

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){
    int hash[1000]={0};
    int *result=(int*)malloc(sizeof(int)*1000);//交集是去重的,最多只有1000个数
    for(int i=0;i<nums1Size;i++){//将nums1录入哈希表
        hash[nums1[i]]++;
    }
    int j=0;
    for(int i=0;i<nums2Size;i++){//将nums2与哈希表比对
        if(hash[nums2[i]]!=0){
            result[j]=nums2[i];
            j++;
            hash[nums2[i]]=0;//手动去重
        }
    }
    *returnSize=j;//这个是主函数输出时用的,跟内部计算关系不大
    return result;
}

将原来的     int result[1000];

改成了         int *result=(int*)malloc(sizeof(int)*1000);

只修改了这一行,虽然非常浅显但一定要知道的错误

这里因为题目数据限制为

  • 1 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 1000

数字大小不会超过1000,可以直接开一个大小为1000的数组(虽然烧了不必要的内存)。实际上返回数组是去重的,题目给的两个数组的重复数据个数不会超过数据个数比较小的那个,这样会比较省内存(但我懒得写了)。

力扣报错runtime error: load of null pointer of type ‘int‘解决思路

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/f3b565e815.html