数据结构-实现数组

来源:互联网 发布:mac word转pdf缺失 编辑:程序博客网 时间:2024/06/02 04:35
 

#include <stdio.h>
#include <string.h>
#include <stdlib.h>//提供exit()函数

typedef struct Array
{
 int cnt; //数组中的有效元素的个数
 int *pBase; //指向为数组分配的首地址
 int len; //数组的长度
} * PARR, ARR; //* PARR代表struct Array * 类型,ARR代表struct Array 类型


void init_arr(PARR pArr, int len); //初始化数组
bool is_empty(PARR pArr); //数组是否为空
void show_arr(PARR pArr); //遍历数组中的值
bool is_full(PARR pArr);
bool append_arr(PARR pArr, int value);//追加
bool insert_arr(PARR pArr, int pos, int value);
bool delete_arr(PARR pArr, int pos);

int main(void)
{
 ARR arr;
 printf("ARR arr的字节数:%d \n", sizeof(arr));
 printf("ARR arr的地址:%p \n", &arr);

 //init_arr(&arr, 0.5); //输出0
 //init_arr(&arr, 1); //输出4
 init_arr(&arr, 6); //输出24
 //show_arr(&arr);
 append_arr(&arr, 1);
 append_arr(&arr, 2);
 append_arr(&arr, 3);
 append_arr(&arr, 4);
 //append_arr(&arr, 5);
 //append_arr(&arr, 6);
 //append_arr(&arr, 7);
 show_arr(&arr);

 insert_arr(&arr, 3, 100);
 show_arr(&arr);

 insert_arr(&arr, 6, 100);
 show_arr(&arr);
 
 delete_arr(&arr, 5);
 show_arr(&arr);
 return 0;
}

void init_arr(PARR pArr, int len)
{
 printf("PARR pArr的字节数:%d \n", sizeof(pArr));

 pArr->pBase = (int *)malloc(sizeof(int)*len);
 printf("分配的字节数:%d \n", sizeof(int)*len);
 printf("(int *)malloc(sizeof(int)*len)返回的的地址:%p \n", (int *)malloc(sizeof(int)*len));
 printf("pArr->pBase保存的地址:%p \n", pArr->pBase);
 printf("pArr->pBase的地址:%p \n", &(pArr->pBase));


 pArr->cnt = 0;
 pArr->len = 6;//初始化长度
 if(NULL == pArr->pBase)
 {
  printf("为数组分配内存失败!\n");
  exit(-1);
 }
 printf("为数组分配内存成功!\n");
}

bool is_empty(PARR pArr)
{
 if(0 == pArr->cnt)
 {
  return true;
 }
 return false;
}

void show_arr(PARR pArr)
{
 if(is_empty(pArr))
 {
  printf("数组为空,没有数值!\n");
 }
 for(int i = 0; i < pArr->cnt; i++)//显示数组中的值
 {
  //pArr->pBase[i];
  printf("%d \t %p", pArr->pBase[i], &pArr->pBase[i]);
 }
 printf("\n");//格式分割
}

bool is_full(PARR pArr)
{
 if(pArr->len == pArr->cnt)
 {
  return true;
 }
 return false;
}

bool append_arr(PARR pArr, int value)
{
 if(is_full(pArr))
 {
  printf("数组已满!\n");
  return false;
 }
 pArr->pBase[pArr->cnt] = value; //pArr->pBase[pArr->cnt - 1]下标访问
 (pArr->cnt)++;
 return true;
}

bool insert_arr(PARR pArr, int pos, int value)
{
 if(pos < 1 || pos > (pArr->cnt + 1))
 {
  printf("你输入的添加位置有误!\n");
  return false;
 }

 for(int i = (pArr->cnt - 1); i >= pos -1; i--)
 {
  pArr->pBase[i + 1] = pArr->pBase[i];
 }
 pArr->pBase[pos-1] = value;
 pArr->cnt++;
 return true;
}

bool delete_arr(PARR pArr, int pos)
{
 if(pos < 1 || pos > pArr->cnt)
 {
  printf("你输入的删除位置有误!");
  return false;
 }
 for(int i = pos; i <= (pArr->cnt - 1); i++)
 {
  pArr->pBase[i - 1] = pArr->pBase[i];
 }
 pArr->cnt--;
 return true;
}

原创粉丝点击