Let's say we have the following structure:
typedef struct array
{
size_t sz_of // sizeof an object;
size_t count;
void* objects;
}Array;
Well, an array which can contain a set of arbitrary types. The following functions are designed to be applied on this structure:
Array* ArrayNew(size_t len, size_t sz_of){
Array* a = malloc(sizeof(Array));
if(a == NULL)
return NULL;
a->sz_of = sz_of;
a->count = len;
a->objects = malloc(len * sz_of);
if(a->objects == NULL){
free(a);
return NULL;
}
return a;
}
void ArrayDestroy(Array* a){
free(a->objects);
free(a);
}
void* ArrayGet(Array* a, size_t i){
if(i > a->count)
return NULL;
return (a->objects + a->sz_of * i);
}
void ArraySet(Array* a, void* v, size_t i){
if(i > a->count)
return;
memcpy(a->objects + a->sz_of * i, v, a->sz_of);
}
We have a function:
- which act as a constructor;
- which act as a destructor;
- which act as a getter;
- which act as a setter.
I have added a function which swap two elements of the array but I am not sure if I do it correctly. Since a char
is 1 byte long, I am temporarily storing an element in a char
array which is sz_of
long:
void ArraySwap(Array* a, size_t x, size_t y){
if(x < a->count && y < a->count){
char t[a->sz_of];
memcpy(t, a->objects + a->sz_of * x, a->sz_of);
memcpy(a->objects + a->sz_of * x, a->objects + a->sz_of * y, a->sz_of);
memcpy(a->objects + a->sz_of * y, t, a->sz_of);
}
}
x
and y
are the indexes of the objects which have to be swapped.
It works well on my configuration, but is it unsafe or a non-standard way to proceed? More globally, if you see something weird, unsafe or non-standard, could you point me out please?
Thanks for your answers.