# include<stdio.h>
# include<malloc.h>
# include<stdlib.h>
# include <stdbool.h>
struct Arr{
int * pBase; //存储的是第一个元素的地址
int len; //数组所能容纳的最大的元素个数
int cnt; //数组的有效个数
};
void init_arr(struct Arr * pArr, int length); //分号不能省
bool append_arr(struct Arr * pArr, int val); //追加
bool insert_arr(struct Arr * pArr, int pos, int val); // pos的值从1开始
bool delete_arr(struct Arr * pArr, int pos, int * pVal);
bool is_empty(struct Arr * pArr);
bool is_full(struct Arr * pArr);
void show_arr(struct Arr * pArr);
void inversion_arr(struct Arr * pArr);
int main(void){
struct Arr arr;
int val;
init_arr(&arr,6);
show_arr(&arr);
append_arr(&arr, 1);
append_arr(&arr, 10);
append_arr(&arr, -3);
append_arr(&arr, 6);
append_arr(&arr, 88);
append_arr(&arr, 11);
show_arr(&arr);
printf("执行删除操作:\n");
delete_arr(&arr,4,&val);
if ( delete_arr(&arr, 4, &val) )
{
printf("删除成功!\n");
printf("您删除的元素是: %d\n", val);
}
else
{
printf("删除失败!\n");
}
show_arr(&arr);
printf("执行追加操作:\n");
insert_arr(&arr,4,8);
show_arr(&arr);
printf("执行倒置操作:\n");
inversion_arr(&arr);
show_arr(&arr);
return 0;
};
void init_arr(struct Arr * pArr,int length){
pArr->pBase = (int *) malloc(sizeof(int) * length);
//pBase为分配空间的首元素的地址
if(NULL == pArr -> pBase)
{
printf("动态内存分配失败!\n");
exit(-1); //终止整个程序
}
else
{
pArr->len = length;
pArr->cnt = 0;
}
}
bool is_empty(struct Arr * pArr)
{
if (0 == pArr->cnt)
return true;
else
return false;
}
bool is_full(struct Arr * pArr)
{
if(pArr->cnt == pArr->len)
return true;
else
return false;
}
void show_arr(struct Arr * pArr)
{
if (is_empty(pArr))
{
printf("数组为空\n");
}
else {
printf("此时数组内容为:");
for (int i = 0; i < pArr->cnt; ++i) {
printf("%d ", pArr->pBase[i]);
}
printf("\n");
}
}
bool append_arr(struct Arr * pArr,int val)
{
//数组满时返回false
if (is_full(pArr))
return false;
//不满时追加
pArr->pBase[pArr->cnt] = val;
(pArr->cnt)++;
return true;
}
bool insert_arr(struct Arr * pArr,int pos,int val)//pos的值从1开始
{
int i;
if(is_full(pArr))
return false;
if(pos<1 || pos>pArr->cnt+1)
return false;
for(i = pArr->cnt-1;i>=pos-1;i--){ //pos后的元素右移,再插入val
pArr->pBase[i+1] = pArr->pBase[i];
}
pArr->pBase[pos-1] = val;
(pArr->cnt)++;
return true;
}
bool delete_arr(struct Arr * pArr,int pos, int * pVal)
{
int i;
if(is_empty(pArr))
return false;
if(pos<1 || pos>pArr->cnt+1)
return false;
*pVal = pArr->pBase[pos-1];
for(i = pos;i<pArr->cnt;++i)
{
pArr->pBase[i-1] = pArr->pBase[i];
}
pArr->cnt--;
return true;
}
void inversion_arr(struct Arr * pArr)
{
int i = 0; //首元素的下标为0
int j = pArr->cnt-1;
int t;
//元素下标最大j和最小i中数据进行互换,之后元素最小下标i++自增和元素最大下标
//j—自减进行数据互换,剩下的元素依次进行类推,直到最中间元素的数据互换完,
//数组总共奇数个元素,则中间元素不存在互换问题,偶数个元素则两两成对无中间元素
while(i<j)
{
t=pArr->pBase[i];
pArr->pBase[i] = pArr->pBase[j];
pArr->pBase[j] = t;
++i;
--j;
}
return;
}
08-07
205
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)