C-Kurs/libgdsl-beispiel: Unterschied zwischen den Versionen
< C-Kurs
(Die Seite wurde neu angelegt: „<pre> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gdsl_types.h> #include <gdsl_stack.h> /** Copies the given data element (a string in...“) |
PaulG (Diskussion | Beiträge) K (verschob „Ckurs/libgdsl-beispiel“ nach „C-Kurs/libgdsl-beispiel“) |
(kein Unterschied)
|
Aktuelle Version vom 5. März 2013, 17:37 Uhr
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <gdsl_types.h> #include <gdsl_stack.h> /** Copies the given data element (a string in our case) */ gdsl_element_t alloc_element(void *elem) { int len = strlen((char *)elem); gdsl_element_t result = malloc(len + 1); memcpy(result, elem, len + 1); return result; } /** Frees memory consumed by the given element */ void free_element(gdsl_element_t e) { free(e); } /** Prints the given element to an arbitrary stream */ void print_element(gdsl_element_t element, FILE *file, gdsl_location_t location, void *user_data) { fprintf(file, "%i: %s\n", location, (char*)element); } /** Call-back function for traversal of data structure */ int do_something(gdsl_element_t element, gdsl_location_t location, void *user_data) { printf("%s", (char*)element); /* just print the element */ return GDSL_MAP_CONT; /* continue traversal */ } #define BUFFER_SIZE 1000 int main(int argc, char **argv) { /* Initialize the stack structure with pointers to alloc- * and free functions */ gdsl_stack_t stack = gdsl_stack_alloc("Mein Stack", alloc_element, free_element); /* Fill the stack dynamically */ char buffer[BUFFER_SIZE]; printf("> "); fgets(buffer, sizeof(buffer)-1, stdin); while (strlen(buffer) > 1) { gdsl_stack_insert(stack, buffer); printf("> "); fgets(buffer, sizeof(buffer)-1, stdin); } /* Traverse stack forward */ printf("map_forward\n-----------\n"); gdsl_stack_map_forward(stack, do_something, NULL); /* Traverse stack backward */ printf("map_backward\n------------\n"); gdsl_stack_map_backward(stack, do_something, NULL); /* printf("\nDump: "); gdsl_stack_write_xml(stack, print_element, stdout, NULL); */ /* Traverse and free stack manually */ while (!gdsl_stack_is_empty(stack)) { gdsl_element_t e = gdsl_stack_remove(stack); free_element(e); } /* Free complete data structure and its contents */ gdsl_stack_free(stack); return EXIT_SUCCESS; }