可变数组

Resizable Array

  • Think about a set of functions that provide a mechanism of resizable array of int.

    • Growable
    • Get the current size
    • Access to the elements

    the Interface


Array array_create(int init_size);
void array_free(Array *a);
int array_size(const Array *a);
int* array_at(Array *a,int index);
void array_inflate(Array *a,int more_size); 

#array.h


#ifndef _ARRAY_H_
#define _ARRAY_H_


typedef struct {
    int *array;
    int size;
}Array;

Array array_create(int init_size);
void array_free(Array *a);
int array_size(const Array *a);
int* array_at(Array *a,int index);
void array_inflate(Array *a,int more_size); 



#endif
#array.c

#include "array.h"


const BLOCK_SIZE = 20;
//typedef struct {
//  int *array;
//  int size;
//}Array;

Array array_create(int init_size){

    Array a;
    a.size = init_size;
    a.array = (int*)malloc(sizeof(int)*a.zise);

    return a;   
}



void array_free(Array *a){

    free(a->array);
    a->array = NULL;
    a->size = 0;
}

//封装 
int array_size(const Array *a){

    return a->size;
} 
int* array_at(Array *a,int index){

    if(index >= a->size){
        array_inflate(a,(index/BLOCK_SIZE+1)*BLOCK_SIZE-a->size);
    }
    return &(a->array[index]);
}
/*
//功能同下 
int array_get(const Array *a,int index){

    return a->array[index]; 
}

void array_set(Array *a,int index,int value){

    a->array[index] = value;
}
*/
void array_inflate(Array *a,int more_size){

    int *p = (int*)malloc(sizeof(int)*(a->size+more_size));
    int i;
    for(i = 0;i<a->size;i++){
        p[i] = a->array[i];
    } 
    free(a->array);
    a->array = p;
    a->size += more_size;
}

int main(int argc,char const *argv[]){

    Array a = array_create(100);
    printf("%d\n",array_size(&a));
    *array_at(&a,0) = 10;
    printf("%d\n",*array_at(&a,0));

    int number = 0;
    int cnt = 0;
    while(number != -1){
        scanf("%d",&number);
        if(number != -1){
            *array_at(&a,cnt++) = number;
        }
    }

    array_free(&a);

    return 0;
}
阅读更多
文章标签: 从语言基础
个人分类: C语言基础加强
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭