1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <malloc.h>
4 #include <stdbool.h>
5
6 //定义了一个数据类型,该数据类型的名字叫struct Arr,含有三个成员
7 struct Arr{
8 int * pBase; //存储数组第一个元素的地址
9 int len; //数组所能容纳的最大元素的个数
10 int cnt; //当前数组有效元素的个数
11 // int increment; //自动增长因子,需要allocate函数,动态追加内存
12 };
13
14 void initArr(struct Arr * pArr, int length);
15 bool appendArr(struct Arr * pArr, int val); //追加
16 bool insertArr(struct Arr * pArr, int pos, int val);//插入, pos的值从1开始
17 bool deleteArr(struct Arr * pArr, int pos, int *pVal); //删除
18 int get();
19 bool isEmpt(struct Arr * pArr);
20 bool isFull(struct Arr * pArr);
21 void sortArr();
22 void showArr(struct Arr * pArr);
23 void inversion(struct Arr *pArr);
24
25 int main(void)
26 {
27 struct Arr arr;
28 int val;
29
30 initArr(&arr, 6);
31 appendArr(&arr, 9);
32 appendArr(&arr, 8);
33
34 inversion(&arr);
35
36 /* appendArr(&arr, 7);
37 appendArr(&arr, 6);
38
39 insertArr(&arr, 1, 11);
40 insertArr(&arr, 5, 22);
41 */
42 showArr(&arr);
43 if(deleteArr(&arr, 1, &val)){
44 printf("删除成功\n");
45 printf("您删除的元素是:%d\n", val);
46 }else{
47 printf("删除失败\n");
48 }
49
50 system("pause");
51 return 0;
52 }
53
54 void initArr(struct Arr *pArr, int length){
55 pArr->pBase = (int *)malloc(sizeof(int) * length);
56 //pArr这个结构体指针变量指向结构体中pBase指针成员
57 //如果分配失败,报错
58 if(NULL == pArr->pBase){
59 printf("动态分配内存失败\n");
60 exit(-1); //终止整个程序
61 }else{
62 pArr->len = length;
63 pArr->cnt = 0;
64 }
65 return;
66 }
67
68 //判断数组为空
69 bool isEmpt(struct Arr * pArr){
70 if(0 == pArr->cnt)
71 return true;
72 else
73 return false;
74
75 }
76
77 bool isFull(struct Arr * pArr){
78 if(pArr->cnt == pArr->len)
79 return true;
80 else
81 return false;
82 }
83
84 void showArr(struct Arr * pArr){
85 //如果数组为空,则提示当前数组为空,否则输出有效内容
86 int i;
87 if(isEmpt(pArr)){
88 printf("当前数组为空!\n");
89 }else{
90 for(i = 0; i<pArr->cnt; ++i){
91 printf("%d ", pArr->pBase[i]);
92 printf("\n");
93 }
94 }
95 }
96
97 bool appendArr(struct Arr * pArr, int val){
98 if(isFull(pArr))
99 return false;
100
101 pArr->pBase[pArr->cnt] = val;
102 (pArr->cnt)++;
103 return true;
104
105 }
106
107 bool insertArr(struct Arr * pArr, int pos, int val){
108 int i;
109 if(isFull(pArr))
110 return false;
111 if(pos<1||pos>pArr->cnt+1)
112 return false;
113
114 for(i = pArr->cnt-1; i>=pos-1; --i){
115 pArr->pBase[i+1] = pArr->pBase[i];
116 }
117 pArr->pBase[pos-1] = val;
118 (pArr->cnt)++;
119 return true;
120 }
121
122 bool deleteArr(struct Arr * pArr, int pos, int *pVal){
123 int i;
124 if(isEmpt(pArr))
125 return false;
126 if(pos<1 || pos > pArr->cnt)
127 return false;
128
129 *pVal = pArr->pBase[pos-1];
130 for(i = pos; i < pArr->cnt; i++){
131 pArr->pBase[i-1] = pArr->pBase[i];
132 }
133 pArr->cnt--;
134 return true;
135 }
136
137 void inversion(struct Arr *pArr){
138
139 int i = 0;
140 int j = pArr->cnt-1;
141 int t;
142
143 while(i < j){
144 t = pArr->pBase[i];
145 pArr->pBase[i] = pArr->pBase[j];
146 pArr->pBase[j] = t;
147 ++i;
148 --j;
149 }
150 }
151