Notice
Recent Posts
Recent Comments
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 개발자
- frontend
- 프로그래밍
- 사물인터넷
- 이웃한 칸
- SNS
- 빅데이터
- 자바독학
- Python
- 백준
- java
- 코딩
- backend
- 코딩독학
- 주가예측
- 프로그램
- 풀스택프레임워크
- 개인프로젝트
- Project
- java정리
- 코테
- 코스닥
- 자바
- Reflex
- 자바정리
- 개발
- 모의 주식
- 프로그래머스
- 코딩테스트
- C++
Archives
- Today
- Total
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으로 크기할당) (0) | 2023.08.25 |
variantArray.c(malloc) (0) | 2023.08.25 |
main.c(스택) (0) | 2023.08.24 |