簡體   English   中英

C - 分配傳遞給函數的指針

[英]C - Malloc-ing a Pointer Passed to a Function

我正在一個編碼挑戰網站上解決一個簡單的問題,但根據編碼環境的設置方式遇到了一個實際的復雜問題。 我正在用 C 解決這個問題。為您提供了函數聲明/參數。 提供的參數是一個指向int數組的指針、一個表示數組元素數量的int以及另一個指向int指針,我假設它是一個我要將解決方案放入的數組:

int* smallerNumbersThanCurrent(int* nums, int numsSize, int* returnSize)
{
    /* My solution... */
}

在將解決方案分配給每個第i個元素的循環中,出現越界運行時錯誤。 上面還有這樣的評論:

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */

顯然表明它指向的任何內存都沒有被分配,這需要與輸入數組的大小相同。 我試圖這樣做:

/* Error-checking */
returnSize = (int*)malloc(numsSize * sizeof(int));
/* Rest of the solution... */

但這會導致緩沖區溢出。 該網站回退了一堆內存地址,顯示錯誤所在,但這不是很有幫助。

顯然,一個草率的解決方案只是重新分配我需要的另一個大小的數組並將指針返回到該數組,但該站點顯然正在檢查指向的數組中的解決方案,因為我沒有分配給它系統報告我的數組為空。

我不確定如何使用int *returnSize ,或者自動化測試套件實際使用它做什么。 誰能告訴我我哪里出錯了,為什么我到目前為止所嘗試的都失敗了? 謝謝你。

編輯:來自網站的問題規范。 它相當缺乏信息,只是簡單地描述了問題本身,而不是務實地描述了骨架是如何設置的。

Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i].

Return the answer in an array.



Example 1:

Input: nums = [8,1,2,2,3]
Output: [4,0,1,1,3]
Explanation: 
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). 
For nums[1]=1 does not exist any smaller number than it.
For nums[2]=2 there exist one smaller number than it (1). 
For nums[3]=2 there exist one smaller number than it (1). 
For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).

Example 2:

Input: nums = [6,5,4,8]
Output: [2,1,0,3]

Example 3:

Input: nums = [7,7,7,7]
Output: [0,0,0,0]



Constraints:

    2 <= nums.length <= 500
    0 <= nums[i] <= 100

該網站是Leetcode ,問題 #1365( https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/ )。 我上面包含的函數聲明是問題開始時存在的全部內容。 我應該注意到我也有多個解決方案在我自己的機器上使用GCC編譯,包括:

main()聲明一個指針,並在函數中為它malloc內存。 main()對數組進行malloc並將其作為參數傳遞。 放棄第三個參數,在函數內部對數組進行malloc並返回指向它的指針。

所以我不確定我做錯了什么。

提供的參數是一個指向 int 數組的指針、一個表示數組元素數量的 int 以及另一個指向 int 的指針,我假設它是一個我要將解決方案放入的數組:

您的假設似乎與returnSize參數的命名returnSize 此外,你的函數可以不通過指針返回到分配的空間returnSize ,因為它是按值傳遞 如果它最初指向一個現有對象,那么您可以通過它操作指向的對象,但函數對指針本身所做的更改對調用者是不可見的。

由於函數的返回類型是int * ,假設函數應該返回一個指向任何分配空間的指針似乎是合理的。 returnSize參數然后可能被用於將分配的空間的大小(或至少使用的元素的數量)傳送回調用者,因為調用者無法僅從指向數據的指針來確定。

也就是說,似乎*returnSize以與numSize參數補充其nums參數相同的方式補充函數的返回值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM