Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.5k views
in Technique[技术] by (71.8m points)

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[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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
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[0] = i;
                   returnArray[1] = j;
               }
            }
        }
    }
    *returnSize = 2;
    return returnArray;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...