如何使用 malloc() 函数来 return 一个数组?

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

我正在尝试解决这个问题:

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

我的代码是:

    /**
 * 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;
}

如您所见,他们在代码的开头添加了注释以提供提示,但我不知道我应该如何在这里使用 malloc() 函数以及具体原因。 如您所见,我尝试使用 malloc() 函数添加第一行,这是我在网上阅读的内容,我认为这会有所帮助,因为我认为它会分配 2 个免费 space 给数组,这意味着我将有足够的内存和 space 来在其中插入 2 个整数。 但是没有用。

我很高兴听到我应该如何以及出于什么原因在这里使用 malloc 函数, 谢谢。

不允许在函数体顶部声明与参数同名的局部变量。你应该给另一个名字。

分配大小也是错误的。大小应该是(元素的数量)乘以(一个元素的大小)。

最后我猜return数组中有效元素的个数应该写到returnSize指向的地方。

试试这个:

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;
}