TwoSum
166
Sep 19, 2020

I solved this question using C language, for me the code 1 did not work and code 2 worked, my question is why can't we use the returnsixe variable directly, why do we need to create an extra variable and assign values to it !!

CODE 1:

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

**CODE 2:**

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