aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorErik Liodden <[email protected]>2017-11-30 08:23:56 +0100
committerErik Liodden <[email protected]>2017-11-30 08:23:56 +0100
commit27697ae4c10b14d96275271e4b22b6578c2aac88 (patch)
tree7a02e5637ecbdb1d1c5c13cef226007384923d99
parent4d9e59da1d5b12b5b8e7e2bf30f438a22aa6e446 (diff)
downloadalgdat-27697ae4c10b14d96275271e4b22b6578c2aac88.tar.gz
improve stack
get and replace a certain value in the stack
-rw-r--r--stack.c29
-rw-r--r--structure.h2
2 files changed, 28 insertions, 3 deletions
diff --git a/stack.c b/stack.c
index 3d2b219..c72a6ca 100644
--- a/stack.c
+++ b/stack.c
@@ -5,6 +5,7 @@
* Erik Liodden
*/
+#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
@@ -46,19 +47,41 @@ void stack_push(struct stack *s, void *elem_addr)
s->log_length++;
}
-void stack_peek(struct stack *s, void *elem_addr)
+void stack_get(struct stack *s, void *elem_addr, int loc)
{
- assert(s->log_length > 0);
- void *source = (char *)s->elems + ((s->log_length-1) * s->elem_size);
+ if (s->log_length > 0 && loc < s->log_length && loc >= 0) {
+ fprintf(stderr, "array out of bounds: size %d, index: %d\n",
+ s->log_length, loc);
+ exit(EXIT_FAILURE);
+ }
+ void *source = (char *)s->elems + (loc * s->elem_size);
memcpy(elem_addr, source, s->elem_size);
}
+void stack_peek(struct stack *s, void *elem_addr)
+{
+ stack_get(s, elem_addr, s->log_length-1);
+}
+
void stack_pop(struct stack *s, void *elem_addr)
{
stack_peek(s, elem_addr);
s->log_length--;
}
+void stack_replace(struct stack *s, void *elem_addr, int loc)
+{
+ if (s->log_length > 0 && loc < s->log_length && loc >= 0) {
+ fprintf(stderr, "array out of bounds: size %d, index: %d\n",
+ s->log_length, loc);
+ exit(EXIT_FAILURE);
+ }
+ if (s->freefn)
+ s->freefn((char *)s->elems + (loc * s->elem_size));
+ void *target = (char *)s->elems + (loc * s->elem_size);
+ memcpy(target, elem_addr, s->elem_size);
+}
+
int stack_length(struct stack *s)
{
return s->log_length;
diff --git a/structure.h b/structure.h
index 5a3be67..8582c2e 100644
--- a/structure.h
+++ b/structure.h
@@ -28,6 +28,8 @@ void stack_dispose(struct stack *s);
void stack_push(struct stack *s, void *elem_addr);
void stack_pop(struct stack *s, void *elem_addr);
void stack_peek(struct stack *s, void *elem_addr);
+void stack_get(struct stack *s, void *elem_addr, int loc);
+void stack_replace(struct stack *s, void *elem_addr, int loc);
int stack_length(struct stack *s);
/****************************************************************************