made examples/demos for vectors && files && lists | also fixed a bug with the vector and list size and popping, explained in the adjacent comment

This commit is contained in:
Odweta
2023-12-22 19:04:08 +01:00
parent 2f1c78ce52
commit b9c93116bc
9 changed files with 146 additions and 75 deletions
+11 -6
View File
@@ -96,12 +96,17 @@ listCleanup(list_t* l) {
void*
listPop(list_t* l) {
vector_t *first_ptr = (vector_t *)vectorPop((vector_t *)l->data);
void *ptr = vectorPop(first_ptr);
l->size -= 1;
if (l->size != 0) {
vector_t *first_ptr = (vector_t *)vectorPop((vector_t *)l->data);
void *ptr = vectorPop(first_ptr);
l->size -= 1;
if (l->size <= l->capacity / 2) l->capacity /= 2;
if (l->capacity == 0) l->capacity = 1;
if (l->size <= l->capacity / 2) l->capacity /= 2;
if (l->capacity == 0) l->capacity = 1;
return ptr;
return ptr;
} else {
// cannot pop when there is no value in the list
return NULL;
}
}
+34 -28
View File
@@ -211,35 +211,41 @@ void*
vectorPop(vector_t* v) {
// capacity is always a power of 2, so a rounding error cannot happen i guess _/-(shi)-\_
switch (v->type) {
case INT:
int *iretval = (int *)(v->data) + v->size-1;
v->size -= 1;
if (v->size <= v->capacity / 2) v->capacity /= 2;
if (v->capacity == 0) v->capacity = 1;
return iretval;
case FLOAT:
float *fretval = (float *)(v->data) + v->size-1;
v->size -= 1;
if (v->size <= v->capacity / 2) v->capacity /= 2;
if (v->capacity == 0) v->capacity = 1;
return fretval;
case CHAR:
char *cretval = (char *)(v->data) + v->size-1;
v->size -= 1;
if (v->size <= v->capacity / 2) v->capacity /= 2;
if (v->capacity == 0) v->capacity = 1;
return cretval;
case VECTOR:
vector_t *vretval = (vector_t *)(v->data) + v->size-1;
v->size -= 1;
if (v->size <= v->capacity / 2) v->capacity /= 2;
if (v->capacity == 0) v->capacity = 1;
if (v->size != 0) {
switch (v->type) {
case INT:
int *iretval = (int *)(v->data) + v->size-1;
v->size -= 1;
if (v->size <= v->capacity / 2) v->capacity /= 2;
if (v->capacity == 0) v->capacity = 1;
return iretval;
case FLOAT:
float *fretval = (float *)(v->data) + v->size-1;
v->size -= 1;
if (v->size <= v->capacity / 2) v->capacity /= 2;
if (v->capacity == 0) v->capacity = 1;
return fretval;
case CHAR:
char *cretval = (char *)(v->data) + v->size-1;
v->size -= 1;
if (v->size <= v->capacity / 2) v->capacity /= 2;
if (v->capacity == 0) v->capacity = 1;
return cretval;
case VECTOR:
vector_t *vretval = (vector_t *)(v->data) + v->size-1;
v->size -= 1;
if (v->size <= v->capacity / 2) v->capacity /= 2;
if (v->capacity == 0) v->capacity = 1;
return vretval;
default:
perror("specify a valid vector type\n");
exit(EXIT_FAILURE);
return vretval;
default:
perror("specify a valid vector type\n");
exit(EXIT_FAILURE);
}
} else {
// cannot pop when there is no value in the vector
return NULL;
}
}