But.. it works.. doesn't?
first a header/source file
/* * file: table.h */ #ifndef TABLE_H #define TABLE_H #ifdef DATATYPE #ifdef BTMAXSIZE #include <stdlib.h> #include <err.h> struct book_strc { DATATYPE data; struct book_strc * prev; } book_stack; /* Book table */ static struct book_strc * book_table[BTMAXSIZE]; /* Number of stacks in table */ static unsigned int tablen = 0; void * xmalloc (size_t siz) { register void * pool = malloc (siz); if (!pool) err (1, "xmalloc"); return pool; } void bspush (unsigned int tentry, DATATYPE val) { struct book_strc * new = (struct book_strc *) xmalloc (sizeof (struct book_strc)); new->data = val; new->prev = book_table[tentry]; tablen++; book_table[tentry] = new; } void bspop (unsigned int tentry, DATATYPE * val) { * val = book_table[tentry]->data; struct book_strc * tmp = book_table[tentry]; book_table[tentry] = book_table[tentry]->prev; free (tmp); tablen--; } #endif #endif #endif
and a main program using it ..
#include <stdio.h> #include <stdlib.h> #define BTMAXSIZE 100 #define DATATYPE char* #include "table.h" int main (void) { char str1[] = "Hello"; char str2[] = "World"; char * str3, * str4; bspush (0, str1); bspush (1, str2); bspop (1, &str4); bspop (0, &str3); printf ("%s %s\n", str3, str4); return 0; }output:
Hello World
Usage:
You declare 2 macros
BTMAXSIZE -> this is the max size of the array of stacks
DATATYPE -> this is the data type of stack objects
then you include the file table.h
this file implement a array of stacks that hold objects of same data type
The design idea is a book table where the stacks are
you can put a book at top of stack by passing the stack number and the object like
bspush (0, 100);
and then retrieve the same item by calling bspop with the number of same stack
and a address of same type object to put the result.. like:
bspop (0, &i);
Nenhum comentário:
Postar um comentário