# c - How to use the malloc() function in order to return an array?

1.0k views

### c - How to use the malloc() function in order to return an array?

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 + nums == 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 = i;
returnSize = 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. by (71.8m points)

It is not allowed to declare local variable that have the same name as an argument at the top of function body. You should give another name.

Also the allocation size is wrong. The size should be (the number of elements) times (the size of one element).

Finally I guess the number of valid elements in the array to return should be written to what is pointed at by `returnSize`.

Try this:

``````int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int *returnArray = 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)
{
returnArray = i;
returnArray = j;
}
}
}
}
*returnSize = 2;
return returnArray;
}
``````