Add array push/pop; fix ghastly memory overrun bug.

This commit is contained in:
David Given 2016-10-02 17:24:31 +02:00
parent 79d4ab1d96
commit b11f96e8fe
2 changed files with 22 additions and 4 deletions

View file

@ -1,6 +1,7 @@
#include <stdlib.h> #include <stdlib.h>
#include <stdbool.h> #include <stdbool.h>
#include <string.h> #include <string.h>
#include <assert.h>
#include "array.h" #include "array.h"
static void extend(struct array* array) static void extend(struct array* array)
@ -8,7 +9,7 @@ static void extend(struct array* array)
if (array->count == array->max) if (array->count == array->max)
{ {
int newmax = (array->max == 0) ? 8 : (array->max * 2); int newmax = (array->max == 0) ? 8 : (array->max * 2);
void** newarray = realloc(array->item, newmax * sizeof(void*)); struct array* newarray = realloc(array->item, newmax * sizeof(*newarray));
array->max = newmax; array->max = newmax;
array->item = newarray; array->item = newarray;
@ -24,16 +25,21 @@ void array_append(void* arrayp, void* value)
array->count++; array->count++;
} }
bool array_contains(void* arrayp, void* value) int array_indexof(void* arrayp, void* value)
{ {
struct array* array = arrayp; struct array* array = arrayp;
int i; int i;
for (i=0; i<array->count; i++) for (i=0; i<array->count; i++)
if (array->item[i] == value) if (array->item[i] == value)
return true; return i;
return false; return -1;
}
bool array_contains(void* arrayp, void* value)
{
return (array_indexof(arrayp, value) != -1);
} }
bool array_appendu(void* arrayp, void* value) bool array_appendu(void* arrayp, void* value)
@ -76,5 +82,13 @@ void array_remove(void* arrayp, void* value)
} }
} }
void* array_pop(void* arrayp)
{
struct array* array = arrayp;
assert(array->count > 0);
return array->item[array->count--];
}
/* vim: set sw=4 ts=4 expandtab : */ /* vim: set sw=4 ts=4 expandtab : */

View file

@ -22,6 +22,10 @@ extern bool array_appendu(void* array, void* value);
extern void array_insert(void* array, void* value, int before); extern void array_insert(void* array, void* value, int before);
extern void array_remove(void* array, void* value); extern void array_remove(void* array, void* value);
extern bool array_contains(void* array, void* value); extern bool array_contains(void* array, void* value);
extern int array_indexof(void* array, void* value);
#define array_push(a, v) array_append(a, v)
extern void* array_pop(void* array);
#endif #endif