• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

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

武飞扬头像
TAIKI_daiji
帮助2

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

349. 两个数组的交集学新通https://leetcode.cn/problems/intersection-of-two-arrays/

出现报错的代码 

  1.  
    /**
  2.  
    * Note: The returned array must be malloced, assume caller calls free().
  3.  
    */
  4.  
    int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){
  5.  
    int hash[1000]={0};
  6.  
    int result[1000];//交集是去重的,最多只有1000个数
  7.  
    for(int i=0;i<nums1Size;i ){//将nums1录入哈希表
  8.  
    hash[nums1[i]] ;
  9.  
    }
  10.  
    int j=0;
  11.  
    for(int i=0;i<nums2Size;i ){//将nums2与哈希表比对
  12.  
    if(hash[nums2[i]]!=0){
  13.  
    result[j]=nums2[i];
  14.  
    j ;
  15.  
    hash[nums2[i]]=0;//手动去重
  16.  
    }
  17.  
    }
  18.  
    *returnSize=j;//这个是主函数输出时用的,跟内部计算关系不大
  19.  
    return result;
  20.  
    }
学新通

 报错描述

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

原因分析 

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

解决方法

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

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

修改后的代码

  1.  
    /**
  2.  
    * Note: The returned array must be malloced, assume caller calls free().
  3.  
    */
  4.  
    int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){
  5.  
    int hash[1000]={0};
  6.  
    int *result=(int*)malloc(sizeof(int)*1000);//交集是去重的,最多只有1000个数
  7.  
    for(int i=0;i<nums1Size;i ){//将nums1录入哈希表
  8.  
    hash[nums1[i]] ;
  9.  
    }
  10.  
    int j=0;
  11.  
    for(int i=0;i<nums2Size;i ){//将nums2与哈希表比对
  12.  
    if(hash[nums2[i]]!=0){
  13.  
    result[j]=nums2[i];
  14.  
    j ;
  15.  
    hash[nums2[i]]=0;//手动去重
  16.  
    }
  17.  
    }
  18.  
    *returnSize=j;//这个是主函数输出时用的,跟内部计算关系不大
  19.  
    return result;
  20.  
    }
学新通

将原来的     int result[1000];

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

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

这里因为题目数据限制为

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

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

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhefkjke
系列文章
更多 icon
同类精品
更多 icon
继续加载