I'm trying to solve this question:
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because
nums[0] + nums[1] == 9, we return [0, 1].
my code is:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
*returnSize = malloc (2 / sizeof(int));
for (int i=0; i<numsSize; i++)
{
for (int j=0; j< numsSize; j++)
{
if (i != j)
{
if(nums[i] + nums[j] == target)
{
returnSize[0] = i;
returnSize[1] = j;
}
}
}
}
return returnSize;
}
as you can see, they added the comment in the beginning of the code to give a hint, but I have no idea how should I use the malloc() function here and for what exact reason. as you can see, I've tried to add the first line with the malloc() function, just from what I have read online and thought this is gonna help, because I thought it's assigning 2 free spaces to the array, which means I'll have plenty of memory and space to insert 2 integers inside of it. But it did not work.
I'll be glad to hear how and for what reason should I use here the malloc function, thanks.
2 / sizeof(int)will result in0, assizeof(int)is likely to be 4 or 8. As tkausl said, you need to multiply here.jati+1instead of 0. That would also make thei != jtest redundant. You can also return the pointer to the array as soon as you have filled it in for the first match of the target value instead of continuing the loops to look for other matches.returnArray[0] = i;returnArray[1] = j;, you can addreturn returnArray;to return straight away. You still need areturnat the end of the function, but that should only be reached if there are no matches. (You could do something to indicate that no match was found, such as setting the array elements to -1 or freeing the memory and returningNULL.)