我寫了一個基本代碼來動態創建一個陣列:
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));
}
我創建了一個函式來從陣列中洗掉元素:
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;
}
當我插入元素時代碼作業正常,但是當我呼叫洗掉函式時它顯示分段錯誤(核心轉儲)。
這是輸出的樣子:
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)
uj5u.com熱心網友回復:
您忘記在洗掉功能中使用scanffor 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()而不是自己撰寫回圈并冒犯錯誤的風險。這在此執行緒中進行了解釋。您可以用以下內容替換回圈:
memmove(&(a->ptr)[i], &(a->ptr)[i 1], (a->used_size - 1 - index)*sizeof(int));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/378655.html
上一篇:矩陣中不斷增長的子串的長度
下一篇:在記憶體塊上實作位移的最佳方法
