2015-04-22 51 views
2

希望我的問題是可讀的。如何檢查指針指向的數組結構是否爲空c?

所以我正在做的是插入一個具有唯一dataIndex的項到數組中,但在插入它之前,我需要檢查dataIndex是否已被使用。

這是我用了兩個結構:

typedef struct item { 
    float key; // the key for deciding position in heap 
    unsigned int dataIndex; // a unique id for each item 
} HeapItem; 

typedef struct heap { 
    HeapItem *H; // the underlying array 
    unsigned int *map; //map[i] is the location of item with dataIndex==i 
    unsigned int n; // the number of items currently in the heap 
    unsigned int size; // the maximum number of items allowed in the heap 
} Heap; 

我做了什麼檢查dataIndex是這樣的:

for (unsigned int i = 0; i < h->n; i++) { 
     if (h->H[i].dataIndex == dataIndex) { 
      return HEAP_FAIL; 
     } 
} 

但這for循環將採取O(N)次,每次我插入的東西,所以我想要做的是這樣的:

if (h->map[dataIndex] != NULL) { 
    return HEAP_FAIL; 
} 

但這段代碼不起作用。

所以我的問題是如何檢查h->H[h->map[dataIndex]]是否爲空?

和下面我分配小時的方式與地圖:

h->H = (HeapItem *)malloc(sizeof(HeapItem)); 
h->map = (unsigned int *)malloc(sizeof(unsigned int)); 

回答

0
if (h->map[dataIndex] != NULL) { 
    return HEAP_FAIL; 
} 

它不會工作,因爲h->map[dataIndex]包含價值,並沒有解決,上述if將覈對價值0。即使你沒有初始化,在任何位置都會有一些垃圾值。

因此,最好的方法是用某個值初始化,比如-1,無窮大或任何您認爲不會出現在實際值範圍內的值。

+0

感謝您的回答。我對指針有一些疑問。這是否意味着當一個指針指向一個地址(例如* p)時,我可以執行if(* p == NULL)'來檢查它?在我的代碼中是'h-> H [0] .key'指向一個浮點數或指向一個地址? –

+0

@LeaneLi你應該檢查'p == NULL',因爲'* p'會在該地址有值,所以你不想檢查NULL值,對不對?您將根據地址進行檢查。 –