![](/img/trans.png)
[英]Do I need to realloc after memmove when remove an element from dynamic array?
[英]Realloc and memmove
我目前有一個結構對數組。 為了插入一個新元素,我將數組重新分配給arraySize + 1,然后從insertIndex,arraySize-insertIndex記憶到目標arr + insertIndex + 1。 這個邏輯有什么問題嗎? 我收到的Uninitialised value was created by a heap allocation
,我懷疑這是因為此實現存在一些錯誤...
代碼在這里:
arraySize++;
arr = realloc(arr,arraySize*sizeof(pair));
...
/* Calculate insertIndex */
...
if (insertIndex+1 < numPairs) {
memmove(arr+insertIndex+1,arr+insertIndex,arraySize-insertIndex-1);
}
您的代碼有兩個問題:
realloc
可能返回0,在這種情況下,舊指針仍然有效。 memmove
隨元素大小移動的元素數量相乘。 sizeof(elementtype)
說sizeof(elementtype)
,寧願使用sizeof *pointer
而不是sizeof(elementtype)
,這樣不容易出錯。
另外,無條件進行調用會稍微簡化您的代碼(總是很棒),並且在多次使用(度量)上可能不會變得更昂貴,甚至可能會更有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.