Cooperate with tree, bsearch, so that I can use C language as far as possible, the following code now provide only append, remove.
Please you give more comments,
Thank you
//-- the dynamic array -
#include
#include
Struct da_struct {
Size_t cap;//number of allocated elements
Size_t len.//number of occupied elements
Size_t size;//the size of an element
Void * root;//pointer to the allocated block
};
//tell the dynamic array, the element size
Struct da_struct da_init (size_t size) {
Size_t cap=100 * 1024;
Void * root=malloc (cap * size);
Return (struct da_struct) {cap, 0, the size, root};
}
//free the memory of the dynamic array
Void da_cleanup (struct da_struct * da) {
Free (da - & gt; Root);
}
//append an object into the dynamic array
//object size should be the same as the to the init function
//return the element address in an array or NULL if the append fails
Void * da_append (struct da_struct * da, void * obj) {
If (da - & gt; Len & gt;=da - & gt; Cap) {
Da - & gt; Cap *=2;
Void * newp=realloc (da - & gt; Root, da - & gt; The size);
if (! Newp) {
return NULL;
}
Da - & gt; The root=newp;
}
Void * PTR=da - & gt; Root + (da - & gt; Len++ - 1) * da - & gt; size;
Memcpy (PTR, obj, da - & gt; The size);
return ptr;
}
//the last element will overwrite the one to be removed
Void * da_remove (struct da_struct * da, void * elem) {
Memcpy (elem, da - & gt; Root + da - & gt; Len - 1, da - & gt; The size);
Return elem.
}
CodePudding user response:
Fine, thumb up, hope that the building Lord continue to work hard, perfect, further perfect,CodePudding user response:
//diff
- memcpy (elem, da - & gt; Root + da - & gt; Len - 1, da - & gt; The size);
+ memcpy (elem, da - & gt; Root + - da - & gt; Len, da - & gt; The size);
CodePudding user response: