Creative Code

main.c(스택을 malloc으로 크기할당) 본문

C Programming

main.c(스택을 malloc으로 크기할당)

빛하루 2023. 8. 25. 11:16

※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