/*                                testStack5.c                        */

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h>
#include "stack5.h"
 
int main(void)
{
    Stack s1, s2;
    initStack(&s1, 10, sizeof(int));        
    initStack(&s2, 10, sizeof(double));
    
    int i;
    i=100;    push(&s1, &i);
    i=200;    push(&s1, &i);
    i=300;    push(&s1, &i);
    
    double d;
    d=1.0;    push(&s2, &d);
    d=2.0;    push(&s2, &d);
    d=3.0;    push(&s2, &d);
    
    pop(&s1, &i);    printf("s1 1st pop() : %d\n", i);
    pop(&s1, &i);    printf("s1 2st pop() : %d\n", i);
    pop(&s1, &i);    printf("s1 3st pop() : %d\n", i);
    
    pop(&s2, &d);    printf("s2 1st pop() : %.2f\n", d);
    pop(&s2, &d);    printf("s2 2st pop() : %.2f\n", d);
    pop(&s2, &d);    printf("s2 3st pop() : %.2f\n", d);
    
    cleanupStack(&s1);
    cleanupStack(&s2);
    
    return 0;
}





/*                      stack5.c                */

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "stack5.h"
 
 
void initStack(Stack *ps, size_t size, size_t eleSize)
{
    ps->tos = 0;
    ps->size = size;
    ps->eleSize = eleSize;
    //ps->pArr = (int *)malloc(sizeof(int) * size);
    ps->pArr = malloc(eleSize*size);
}
 
 
void cleanupStack(Stack *ps)
{
    free(ps->pArr);    
    ps->pArr=NULL;
}
 
void push(Stack *ps, const void *pData/*, size_t eleSize*/)
{
    assert(ps->tos < ps->size);
    
    //ps->pArr[ps->tos] = data;
    memcpy((unsigned char *)ps->pArr + ps->tos * ps->eleSize, pData, ps->eleSize);
    ++ps->tos;
}
 
void pop(Stack *ps, void *pData)
{
    assert(ps->tos > 0);
    
    --ps->tos;
    //return ps->pArr[ps->tos];
    memcpy(pData, (unsigned char *)ps->pArr + ps->tos * ps->eleSize, ps->eleSize);
}
 
 





/*                        stack5.h                        */

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#ifndef STACK5_H
#define STACK5_H
 
typedef struct{
    void *pArr;
    size_t eleSize;
    size_t size; 
    int tos;
} Stack;
 
void initStack(Stack *ps, size_t size, size_t eleSize);
void cleanupStack(Stack *ps);
void push(Stack *ps, const void *pData);
void pop(Stack *ps, void *pData);
 
#endif




Posted by 차희빈

차희빈

달력