Dynamic Array with structure support
/******************************************************************************
New Era Datastructure
Designed by Daipayan Bhowal
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int SIZE = 64; // set default size of dynamic array as 64
enum type_t {
INT,
FLOAT,
CHAR,
STRING,
STRUCT
};
int get_size_type(enum type_t t, int struct_size)
{
int mulitplier;
switch(t)
{
case INT:
mulitplier = sizeof(int);
break;
case FLOAT:
mulitplier = sizeof(float);
break;
case CHAR:
mulitplier = sizeof(char);
break;
case STRING:
mulitplier = 128*sizeof(char);
break;
case STRUCT:
mulitplier = struct_size;
break;
}
return mulitplier;
}
void* dyna_array_decl(enum type_t t,int size,int struct_size)
{
void* ptr;
int multiplier=0;
SIZE = size;
multiplier=get_size_type(t,struct_size);
ptr =malloc(multiplier*size);
return ptr;
}
void *dyna_array_expand(void *ptr, enum type_t t, int expand_size)
{
void *expanded_array;
expanded_array= realloc(ptr,expand_size);
return expanded_array;
}
void *dyna_array_shrink(void *ptr, enum type_t t, int shrink_size)
{
void *shrinked_array;
shrinked_array= realloc(ptr,SIZE-shrink_size);
return shrinked_array;
}
void dyna_array_set(void* ptr,enum type_t t, int index,void *data,int struct_size)
{
void *pos;
int multiplier=get_size_type(t,struct_size);
if(index > SIZE)
{ SIZE += 32; // expand the size
ptr=dyna_array_expand(ptr,t,32); // expand the array by 32
}
pos = ptr + multiplier*index;
memcpy(pos, data,multiplier );
return;
}
void *dyna_array_get(void* ptr,enum type_t t, int index,int struct_size)
{
void *pos;
int multiplier=get_size_type(t,struct_size);
pos = ptr + multiplier*index;
return pos;
}
int main()
{
int *a = (int*) dyna_array_decl(INT,5,0); // int a[5]
int b = 5;
dyna_array_set(a,INT,0,&b,0); // int a[0] = b;
int *c= dyna_array_get(a,INT,0,0); // a[0];
printf("%d\n", *c);
free(a);
return 0;
}
Comments
Post a Comment