簡體   English   中英

優先隊列的這部分C代碼如何工作?

[英]How does this segment of C code for a priority queue work?

我對這條線有些不知所措:

 Entry** newHeap = (Entry**)malloc(sizeof(Entry*) * newHeapLength);

在此代碼中:

 /**
     * Expands the heap array of the given priority queue by 
     *   replacing it with another that is double its size.
     *
     * @param  pq  the priority queue whose heap is to be doubled in size
     * return  1 for successful expansion or an error code:
     */
    int expandHeap (PriorityQueue *pq)
    {
        int returnCode = 1;
        int newHeapLength = pq->heapLength * 2;
        Entry** newHeap = (Entry**)malloc(sizeof(Entry*) * newHeapLength);
        if (newHeap != NULL) 
        {
            int index;
            for (index = 0; index < pq->heapLength; index++) 
            {
                newHeap[index] = pq->heap[index];
            }
            free(pq->heap);
            pq->heap = newHeap;
            pq->heapLength = newHeapLength;
        }
        else
        {
            returnCode = -1;  // TODO: make meaningful error codes
        }
        return returnCode;
    }
Entry** newHeap = (Entry**)malloc(sizeof(Entry*) * newHeapLength);
      |                      |
newHeap is a             malloc allocates a chunk in memory that is the size of 
pointer to a             a pointer to an Entry times newHeapLength
pointer to an Entry

它只是在運行時為您分配一個數組。 通常,數組的大小必須在編譯時指定。 但是這里是在運行時指定的,它是newHeapLength 該數組中的每個條目(“單元格”)必須能夠在其中存儲Entry*類型的值。 在C中,數組是連續的,因此數組的總大小(以字節為單位)只是兩個數字的乘積: sizeof(Entry*) * newHeapLength 現在,可以使用newHeap以通常的方式來尋址此數組:例如newHeap[8] 當然,如果8 >= newHeapLength ,這將是訪問分配的區域,這是不好的

對於存儲10個int的數組, int ia[10]; ia的類型為int *更正:幾乎。但是,出於解釋的目的,我們可以假裝為 )。 在這里,類似地,對於存儲類型為Entry*值的數組,類型為(Entry*)* 簡單。 :)

當然,您必須將malloc的返回值轉換為您的類型,以便能夠使用該地址尋址該數組。 malloc本身返回一個地址為void* 含義。 它所指向的存儲單元的大小被稱為未知 當我們說ia的類型為int* ,實際上是說它所指向的存儲單元的大小為sizeof(int) 因此,當我們編寫ia[3] ,它實際上被轉換為*(ia+3) ,實際上是*(int*)(void*)( (unsigned int)(void*)ia + 3*sizeof(int) ) 換句話說,編譯器僅將sizeof(int)添加到起始地址三倍,從而“跳過”三個sizeof(int)寬的內存單元。 對於newHeap[8] ,它將僅“跳”過8個sizeof(Entry*)寬的存儲單元,以獲取該數組中第9個條目的地址(從1開始計數)。

另外,請參見哈希數組樹 ,以了解幾何擴展的替代方法,即代碼正在執行的操作。

暫無
暫無

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

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