Strange Runtime Error for C: load of null pointer of type 'const int'


  • 0
    R

    Hi, below is my code. It runs fine but will get an error whenever I submit: load of null pointer of type 'const int'

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

    I think the problem is related with the outer loop. That is, if I change the codes to this, it works with error:

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

    I am wondering why it's happening?

    Many thanks.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.