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
- 프로그래밍
- 자바독학
- Project
- 모의 주식
- Python
- java
- 이웃한 칸
- 자바정리
- Reflex
- 빅데이터
- SNS
- 개발
- 코딩독학
- 프로그래머스
- 사물인터넷
- 프로그램
- 주가예측
- 코딩테스트
- backend
- 개발자
- 백준
- 풀스택프레임워크
- C++
- 코딩
- 개인프로젝트
- java정리
- 코테
- frontend
- 자바
- 코스닥
Archives
- Today
- Total
Creative Code
main.c(스택을 malloc으로 크기할당) 본문
※main.c파일
#include <stdio.h>
#include "stack.h"
int main(void)
{
Stack s1, s2;
initStack(&s1,10);
initStack(&s2,100);
push(&s1,100); //구조체 자료는 인자를 전달할 때 오버헤드를 줄이기 위해 포인터를 쓴다.
push(&s1,200);
push(&s1,300);
printf("s1 1st pop() : %d\n",pop(&s1));
printf("s1 2nd pop() : %d\n",pop(&s1));
printf("s1 3rd pop() : %d\n",pop(&s1));
push(&s2,900);
push(&s2,800);
push(&s2,700);
printf("s2 1st pop() : %d\n",pop(&s2));
printf("s2 2nd pop() : %d\n",pop(&s2));
printf("s2 3rd pop() : %d\n",pop(&s2));
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 "stack.h"
void initStack(Stack *s, int size)
{
s->array = malloc(sizeof(int)*size);
assert(s->array /*!= NULL*/);
// 괄호안에 조건식을 주고 조건식이 참이면 프로그램이 계속 진행, 거짓이면 프로그램 중단
s->size = size;
s->tos = 0;
}
void cleanupStack(Stack *s) // initStack을 통해 할당한 메모리를 cleanupStack을 통해 해제
{
free(s->array);
}
void push(Stack *s, int data)
{
/*if (s->tos == s->size) {
fprintf(stderr,"stack is full\n");
exit(1);
}*/
assert(s->tos != s->size);
s->array[s->tos] = data;
++s->tos;
}
int pop(Stack *s)
{
/*if (s->tos == 0) {
fprintf(stderr,"stack is empty\n");
exit(2);
}*/
assert(s->tos!= 0);
--s->tos;
return s->array[s->tos];
}
'C Programming' 카테고리의 다른 글
main.c(queue) (0) | 2023.08.25 |
---|---|
main.c(스택-메모리함수사용) (0) | 2023.08.25 |
variantArray.c(malloc) (0) | 2023.08.25 |
main.c(스택) (0) | 2023.08.24 |
main.c(볼링보드판) (0) | 2023.08.24 |