Cスタック、運転時タイプ挷定


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#if __STDC_VERSION__ >= 199901L
	#include <stdbool.h>
	#define C99
#else
	typedef enum {false, true} bool;
#endif

typedef struct _stack {
    size_t size;
    size_t capacity;
    char * data;
    size_t element_size;
}Stack, *pStack;

/**
 * specified each element sizt which store in stack.
 * return stack pointer.
 */
void * stack_new(size_t element_size);

/**
 * Release stack memory
 */
void stack_free(pStack ptr);

/**
 * Push value into stack,
 */
bool stack_push(pStack ptr, void * value);

/**
 * Pop from stack
 */
void stack_pop(pStack ptr);

/**
 * Return the top element of stack
 */
void * stack_top(pStack ptr);

/**
 * Return stack size
 */
size_t stack_size(pStack ptr);

typedef struct _stu {
    int no;
    char name[20];
}Student, *pStudent;

void * stack_new(size_t element_size)
{
    pStack ptr = (pStack)calloc(1, sizeof(Stack));
    if (NULL == ptr){
        fprintf(stderr, "stack allocate error
"); } ptr->element_size = element_size; ptr->data = NULL; ptr->size = 0; ptr->capacity = 0; return ptr; } void stack_free(pStack ptr) { free(ptr->data); ptr->size = 0; free(ptr); } bool stack_push(pStack ptr, void * value) { if (ptr->data == NULL) { ptr->data = calloc(1, ptr->element_size); if (ptr->data == NULL) { exit(EXIT_FAILURE); } memcpy(ptr->data, (char*)value, ptr->element_size); ptr->size = 1; } else { if (ptr->capacity <= ptr->size){ ptr->data = realloc(ptr->data, ptr->size * ptr->element_size + ptr->element_size); memcpy(ptr->data + ptr->element_size * ptr->size, (char *)value, ptr->element_size); ptr->size += 1; ptr->capacity += 1; } else { memcpy(ptr->data + ptr->element_size * ptr->size, (char *)value, ptr->element_size); ptr->size += 1; } } return true; } void stack_pop(pStack ptr) { ptr->size -= 1; } void * stack_top(pStack ptr) { return ptr->data + ((ptr->size - 1) * ptr->element_size); } size_t stack_size(pStack ptr) { return ptr->size; }
/* Test */
int main(void)
{
    int value = 10, v = 11;
    Student s1 = {12, "student1"},s2 = {13, "student2"}, 
            s3 = {15, "stu3"}, *sptr;
    pStack ps = stack_new(sizeof(Student));
    pStack p = stack_new(sizeof(int));

    stack_push(p, &value);
    stack_push(p, &v);
    printf("%d
", *((int*)stack_top(p))); stack_pop(p); printf("%d
", *((int*)stack_top(p))); stack_free(p); stack_push(ps, &s1); stack_push(ps, &s2); sptr = (pStudent)stack_top(ps); printf("no: %d, name: %s
", sptr->no, sptr->name); stack_pop(ps); stack_push(ps, &s3); sptr = (pStudent)stack_top(ps); printf("no: %d, name: %s
", sptr->no, sptr->name); stack_free(ps); exit(EXIT_SUCCESS); }