用c实现部分java数组功能,很烂,留个参考吧

#include<stdio.h>
#include<malloc.h>
void initMyarry(struct Myarry *arr);
int isFull(struct Myarry *arr);
void expandMyarry(struct Myarry *arr);
void show(struct Myarry * arr);
void add(struct Myarry *arr,int data);
struct Myarry{
   //数组的首地址
   int * firstAddress;
    //当前数组的大小
   int currentLength;
    //初始化数组大小
   int initLength;
    //当前元素
   int current;
  //增长因子
   double times;


};
main(){
  struct Myarry myarry;
 //初始化数组
  initMyarry(&myarry);
  //增加元素
  int i = 1 ;
  for( ; i <=25 ; i++){
      add(&myarry,i);
  }


 //show出元素
  show(&myarry);








}


//判断数组是否已经满了
int isFull(struct Myarry *arr){


  if(arr->current > arr->currentLength){
    return 1;
  }else{
    return  0;
  }


}


//按照增长因子来增加数组长度
void expandMyarry(struct Myarry *arr){
   printf("expandMyarry");
  //开辟新的空间
   int spaceSize = arr->currentLength + arr->initLength * arr->times ;
   printf("spaceSize = %d\n",spaceSize);
   int * newSpaceAddress = (int * ) malloc(sizeof(int) * spaceSize );
   if(newSpaceAddress==NULL){
     printf("has no nough space for newSpaceAddress ");
     exit(1);
   }else{
        //复制元素
      int i = 0;
      for(; i < arr->current ; i++){
        *(newSpaceAddress + i ) =  *(arr->firstAddress + i );


      }
      arr->currentLength = spaceSize;
      arr->firstAddress = newSpaceAddress;


   }






}


//在数组末尾插入数据
void add(struct Myarry *arr,int data){
   // printf("data = %d",data);
    //判断数组是否已经满0
     // 1 是
     if( isFull(arr)){


        expandMyarry(arr);
        add(arr,data);
     }
      // 2 否
     else{
         printf("\n");
          *( arr->firstAddress + arr->current ) =  data;
          arr->current += 1;
     }






}


//显示数组里面的值
void show(struct Myarry * arr){
    int i = 0;
    for(;i < arr->current ; i++){
        printf("arr[%d] = %d\n" ,i , *(arr->firstAddress + i));
    }
}


//初始化数组
void initMyarry(struct Myarry * arr){
    //当前数组大小为20
    arr->currentLength = 20;
    //初始化数组大小
    arr->initLength = 20;
    //增长因子为1.5
    arr->times = 1.5;
    //当前元素为0
    arr->current=0;
    //开辟空间
    arr->firstAddress = (int *)malloc(sizeof(int)*(arr->currentLength));
     if(arr->firstAddress == NULL){
        printf("has no enough space");
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值