簡體   English   中英

刪除數組中的元素時出現分段錯誤(核心轉儲)錯誤

[英]Segmentation fault (core dumped) error while deletion of an element in an array

我寫了一個基本代碼來動態創建一個數組:

void makeArray(struct Array * a)
{
    int capacity, need;
    printf("Enter the capacity of the array you want: ");
    scanf("%d", &capacity);
    printf("Enter the capacity you are going to use: ");
    scanf("%d", &need);
    a -> used_size = need;
    a -> total_size = capacity;
    a -> ptr = (int*)malloc (capacity * sizeof(int));
}

我創建了一個 function 來從數組中刪除元素:

void indDeletion(struct Array * a)
{
    int index;
    printf("Enter the position you would like to delete the number in: ");
    for(int i = index; a -> used_size - 1; i++)
    {
        a -> ptr[i] = a -> ptr[i+1];
    }
    a -> used_size -= 1;

}

當我插入元素時代碼工作正常,但是當我調用刪除 function 時,它顯示分段錯誤(核心轉儲)。

這是 output 的樣子:

Enter the capacity of the array you want: 100
Enter the capacity you are going to use: 4
Enter element 0: 1
Enter element 1: 2
Enter element 2: 3
Enter element 3: 4
Element 0: 1
Element 1: 2
Element 2: 3
Element 3: 4
Enter the position you would like to insert the number in: 3
Enter the number: 123
Insertion was successful
Element 0: 1
Element 1: 2
Element 2: 3
Element 3: 123
Element 4: 4
Segmentation fault (core dumped)

您忘記在刪除scanf中掃描index

此外,此代碼看起來不正確:

    for(int i = index; a -> used_size - 1; i++)
    {
        a -> ptr[i] = a -> ptr[i+1];
    }

條件a -> used_size -1永遠不會改變,因為您永遠不會在循環中修改a -> used_size 所以要么循環永遠不會運行,要么永遠運行。

另一點 - 移動元素時,您可以使用像memmove()這樣的大容量 function 而不是自己編寫循環並冒犯錯誤的風險。 這在此線程中進行了解釋。 您可以將循環替換為:

memmove(&(a->ptr)[i], &(a->ptr)[i+1], (a->used_size - 1 - index)*sizeof(int));

暫無
暫無

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

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