Notice
Recent Posts
Recent Comments
Creative Code
main.c(스택-메모리함수사용) 본문
※main.c파일
#include <stdio.h>
#include "stack.h"
int main(void)
{
Stack s1, s2;
initStack(&s1,10,sizeof(int));
initStack(&s2,100,sizeof(double));
int i;
i = 100; push(&s1,&i);
i = 200; push(&s1,&i);
i = 300; push(&s1,&i);
int re1;
pop(&s1,&re1); printf("s1 1st pop() : %d\n", re1);
pop(&s1,&re1); printf("s1 2nd pop() : %d\n", re1);
pop(&s1,&re1); printf("s1 3rd pop() : %d\n", re1);
double d;
d = 1.1; push(&s2,&d);
d = 2.2; push(&s2,&d);
d = 3.3; push(&s2,&d);
double re2;
pop(&s2,&re2); printf("s2 1st pop() : %f\n",re2);
pop(&s2,&re2); printf("s2 2nd pop() : %f\n",re2);
pop(&s2,&re2); printf("s2 3rd pop() : %f\n",re2);
cleanupStack(&s1);
cleanupStack(&s2);
return 0;
}
※stack.h파일
#ifndef STACK_H
#define STACK_H
typedef struct stack {
int *array;
int tos;
int size;
}Stack;
void initStack(Stack *s, int size);
void cleanupStack(Stack *s);
void push(Stack *s, int data);
int pop(Stack *s);
#endif
※stack.c파일
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include "stack.h"
void initStack(Stack *s, int size, int eleSize)
{
s->array = malloc(eleSize*size);
assert(s->array);
s->eleSize = eleSize;
s->size = size;
s->tos = 0;
}
void cleanupStack(Stack *s)
{
free(s->array);
}
void push(Stack *s,void *pData)
{
assert(s->tos != s->size);
//memcpy(&s->array[s->tos],pData,s->eleSize); // void 포인터는 역참조할 때 타입캐스팅을 하고 참조해야한다.
memcpy((unsigned char *)s->array + s->eleSize * s->tos, pData,s->eleSize);
++s->tos;
}
void pop(Stack *s, void *pData)
{
assert(s->tos!= 0);
--s->tos;
//memcpy(pData,&s->array[s->tos],s->eleSize);
memcpy(pData,(unsigned char *)s->array + s->eleSize * s->tos, s->eleSize);
}
'C Programming' 카테고리의 다른 글
main.c(queue 구조체) (0) | 2023.08.25 |
---|---|
main.c(queue) (0) | 2023.08.25 |
main.c(스택을 malloc으로 크기할당) (1) | 2023.08.25 |
variantArray.c(malloc) (0) | 2023.08.25 |
main.c(스택) (0) | 2023.08.24 |