使用指標刪除陣列元素的C程式
問題
編寫一個C程式,在執行時由使用者刪除陣列中的一個元素,並在刪除後將結果顯示在螢幕上。如果要刪除的元素不在陣列中,則需要顯示“無效輸入”。
解決方案
陣列用於在一個名稱下儲存一組公共元素。
陣列操作如下:
- 插入
- 刪除
- 搜尋
演算法
參考一個演算法,使用指標刪除陣列中的元素。
步驟 1 - 宣告並讀取元素個數。
步驟 2 - 在執行時宣告並讀取陣列大小。
步驟 3 - 輸入陣列元素。
步驟 4 - 宣告一個指標變數。
步驟 5 - 在執行時動態分配記憶體。
步驟 6 - 輸入要刪除的元素。
步驟 7 - 刪除後,元素向左移動一個位置。
示例
陣列大小為:5
陣列元素如下:
1 2 3 4 5
輸入要刪除的元素的位置:4
輸出如下:
After deletion the array elements are: 1 2 3 5
示例
以下是使用指標將元素插入陣列的C程式:
#include<stdio.h> #include<stdlib.h> void delete(int n,int *a,int pos); int main(){ int *a,n,i,pos; printf("enter the size of array:"); scanf("%d",&n); a=(int*)malloc(sizeof(int)*n); printf("enter the elements:
"); for(i=0;i<n;i++){ scanf("%d",(a+i)); } printf("enter the position of element to be deleted:"); scanf("%d",&pos); delete(n,a,pos); return 0; } void delete(int n,int *a,int pos){ int i,j; if(pos<=n){ for(i=pos-1;i<n;i++){ j=i+1; *(a+i)=*(a+j); } printf("after deletion the array elements is:
"); for(i=0;i<n-1;i++){ printf("%d
",(*(a+i))); } } else{ printf("Invalid Input"); } }
輸出
執行上述程式時,會產生以下輸出:
enter the size of array:5 enter the elements: 12 34 56 67 78 enter the position of element to be deleted:4 After deletion the array elements are: 12 34 56 78
廣告