#include <stdio.h>
#include <stdlib.h>

typedef struct{
	int size;
	int *a;
	int *b;
} array;

array* create(){
	array *t;
	t=(array *)malloc(sizeof(array));
	if(t==NULL){
		printf("ERROR\n");
		return NULL;
	}
	t->size=64;
	t->a=(int *)malloc(t->size*sizeof(int));
	if(t->a==NULL){
		printf("ERROR\n");
		return NULL;
	}

	t->b=(int *)malloc(t->size*sizeof(int));
	if(t->b==NULL){
		printf("ERROR\n");
		return NULL;
	}
	int i=0;	
	for(i=0;i<t->size;i++){
		t->b[i]=0;
	}

	return t;
}

void destroy(array *t){
	free(t->a);
	free(t->b);
	free(t);
}

void u_double(array *t){
	int *temp=(int *)malloc(t->size*2*sizeof(int));
	if(temp==NULL){
		printf("ERROR\n");
		exit(1);
	}
	
	int i;
	for(i=0;i<t->size;i++){
		temp[i] = t->a[i];
	}
	
	free(t->a);
	t->a=temp;


	int *tempBits=(int *)malloc(t->size*2*sizeof(int));
	if(tempBits==NULL){
		printf("ERROR\n");
		exit(1);
	}	

	for(i=0;i<t->size;i++){
		tempBits[i] = t->b[i];
	}
	
	i=t->size; //initialize new segment
	for(i=t->size;i<t->size*2;i++){
		tempBits[i] = 0;
	}

	free(t->b);
	t->b=tempBits;


	t->size=2*t->size;
}

void set(array *t, int i, int value){
	while(i >= t->size){
		u_double(t);
	}
	
	t->a[i]=value;
	t->b[i]=1;//set used bit to 1
}

int get(array *t, int i){
	while(i > t->size){ //not needed now
		u_double(t);
	}
	if(t->b[i]==0){
		printf("ERROR: TRYING TO ACCESS UNSET SLOT:%d\n",i);
		exit(1);
	}

	return t->a[i];
}
 
int main(){
	int i;
	array *A = 	create();
	for(i=0; i<1000; i++)
		set(A,i,i);
	for(i = 0; i<1000; i++)
	printf("%d ", get(A,i));
	printf("\n");
	destroy(A);
}