/* Note: The returned array must be malloced,
assume caller calls free(). */
int* twoSum(int* nums, int numsSize, int target) {
int *ans; //why error
for(int i = 0; i < numsSize; i++){
for(int j = i+1; j < numsSize; j++){
if(nums[i] + nums[j] == target){
ans[0] = i;
ans[1] = j;
break;
}
}
}
return ans;
}
Why code above is incorrect and code below correct (with malloc
added)?
/* Note: The returned array must be malloced,
assume caller calls free(). */
int* twoSum(int* nums, int numsSize, int target) {
int *ans = (int*)malloc(2*sizeof(int)); //why not error
for(int i = 0; i < numsSize; i++){
for(int j = i+1; j < numsSize; j++){
if(nums[i] + nums[j] == target){
ans[0] = i;
ans[1] = j;
break;
}
}
}
return ans;
}