zoukankan      html  css  js  c++  java
  • leetcode 报错runtime error: load of null pointer of type 'int'

    1.题目

    Leetcode 1两数之和

    给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

    你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

    示例:

    给定 nums = [2, 7, 11, 15], target = 9
    因为 nums[0] + nums[1] = 2 + 7 = 9
    所以返回 [0, 1]

    题目链接

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

    2.函数原型

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

    3.执行报错信息

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

     4.原因分析

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

    修改方法一般有3种:

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

    2)static修饰变量

    3)使用全局变量

    5.代码修改

    /**
     * Note: The returned array must be malloced, assume caller calls free().
     */
    int* twoSum(int* nums, int numsSize, int target, int* returnSize){
    
        static int a[2] = {0};
        
        for(int i = 0; i < numsSize-1; i++)
        {
            for(int j = i + 1; j < numsSize; j++)
            {
                if((nums[i] + nums[j]) == target) {
                    a[0] = i;
                    a[1] = j;
                    *returnSize = 2;
                    return a;
                }    
            }    
        }
        return a;
    }
    stay hungry, stay foolish
  • 相关阅读:
    MySQL 存储过程实例
    [MySQL优化] -- 如何了解SQL的执行频率
    [MySQL优化] -- 如何定位效率较低的SQL
    [MySQL优化] -- 如何查找SQL效率地下的原因
    [MySQL优化] -- 如何使用SQL Profiler 性能分析器
    2020.10.09软件更新公告
    2020.04.12软件更新公告
    2020.04.11软件更新公告
    2020.02.21软件更新公告
    程序员调用MODI的正确姿势
  • 原文地址:https://www.cnblogs.com/zygote/p/13192620.html
Copyright © 2011-2022 走看看