HuntnGather – Blame information for rev 43

Subversion Repositories:
Rev:
Rev Author Line No. Line
1 office 1 ///////////////////////////////////////////////////////////////////////////
2 // Copyright (C) 2021 Wizardry and Steamworks - License: MIT //
3 ///////////////////////////////////////////////////////////////////////////
4 // //
5 // stringStack //
6 // //
7 // An implementation of a stack of strings. //
8 // Implemented functions: //
9 // - push //
10 // - pop //
11 // - is empty //
12 // - count //
13 // - size //
14 // - print //
15 // //
16 ///////////////////////////////////////////////////////////////////////////
17  
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <dirent.h>
22  
23 #include <sys/types.h>
24 #include <sys/stat.h>
25  
26 #include "StringStack.h"
27  
28 /*
29 * Creates a new stringStack with a given size.
30 */
31 stringStack* stringStackCreate(unsigned int size) {
31 office 32 stringStack *s;
33 s = malloc(sizeof(*s));
43 office 34 if ((s->store = malloc(size * sizeof(*s->store))) == NULL) {
35 free(s);
36 s = NULL;
1 office 37 return NULL;
43 office 38 }
1 office 39 s->size = size;
40 s->top = 0;
41 return s;
42 }
43  
44 /*
45 * Clears a stringStack and returns a pointer to a new empty stack.
46 */
47 stringStack* stringStackClear(stringStack *s) {
43 office 48 if (s != NULL) {
1 office 49 free(s);
43 office 50 s = NULL;
51 }
1 office 52 return stringStackCreate(1);
53 }
54  
55 /*
56 * Pushes an element onto the stringStack.
57 */
58 void stringStackPush(stringStack *s, char *e) {
59 if (s->top > s->size - 1)
31 office 60 s->store = realloc(s->store, ++s->size * sizeof(*s->store));
61 s->store[s->top] = malloc((strlen(e) + 1) * sizeof(*s->store[s->top]));
1 office 62 strncpy(s->store[s->top], e, strlen(e) + 1);
63 ++s->top;
64 }
65  
66 /*
67 * Pops an element off the stringStack or returns NULL in case the
68 * stack is empty.
69 */
70 char *stringStackPop(stringStack *s) {
71 char *e;
72 if (stringStackIsEmpty(s))
73 return NULL;
74 --s->top;
31 office 75 e = malloc((strlen(s->store[s->top]) + 1) * sizeof(*e));
1 office 76 strncpy(e, s->store[s->top], strlen(s->store[s->top]) + 1);
77 free(s->store[s->top]);
43 office 78 s->store[s->top] = NULL;
1 office 79 return e;
80 }
81  
82 /*
83 * Delete a stringStack.
84 */
85 void stringStackDestroy(stringStack *s) {
31 office 86 char *e;
1 office 87 while(!stringStackIsEmpty(s)) {
31 office 88 e = stringStackPop(s);
89 free(e);
43 office 90 e = NULL;
1 office 91 }
92 free(s);
43 office 93 s = NULL;
1 office 94 }
95  
96 /*
97 * Prints out the elements of the stringStack.
98 */
99 void stringStackPrint(stringStack *s) {
100 int i;
101 if (stringStackIsEmpty(s)) {
102 printf("Stack is empty.\n");
103 return;
104 }
105 printf("Elements in the stack: ");
106 i = s->top - 1;
107 do {
108 printf("%s ", s->store[i]);
109 } while (--i > -1);
110 printf("\n");
111 }