C语言——动态数组堆栈
环境:Linux18.04
前言:
对于数组而言,首先想到就是可以用来存放一些值,但是如何操作和分配里面有很多的东西可以学习,对于数组,我们只需要知道其首地址,全局还是局部,数据是否溢出这三个方面着手就好。这里介绍的动态数组是一个全局变量,我们会定义一个指针类型,因为指针和数组其实可以互换的。这里的动态数组堆栈主要功能有压栈(push)、出栈(pop)、创建(create)、销毁(empty)和遍历(printf)。
一、压栈(push)
void push(int data)
{
if((stack_size -1) >= top_cnt ) //判断数组是否full
{
top_cnt += 1;
stack[top_cnt] = data;
}
else
printf("the arr is full!");
}
二、出栈(pop)
void pop(void)
{
if(top_cnt > -1) //判断数组是否为空
top_cnt -= 1;
}
三、创建(create)
void create_stack(int size)
{
stack_size = size;
stack = (int *)malloc(stack_size * sizeof(int)); //在内存堆区分配一个自定义大小的数组
if(stack == NULL)
printf("malloc is fail!");
}
四、销毁(empty)
void destroy_stack(void) //销毁数组
{
if(stack != NULL)
{
stack_size = 0;
free(stack); //释放数组在堆区的的内存
stack = NULL;
}
}
五、遍历(printf)
void stack_printf(void)
{
int i;
i = top_cnt;
if(i == -1)
printf("the stack is empty!\n");
while(i != -1)
{
printf("%d ", stack[i]); //打印数组存放的数据
i--;
}
printf("\n");
}
六、具体代码
#include<stdio.h>
#include<malloc.h>
static int *stack;
static int stack_size;
static int top_cnt= -1;
void create_stack(int size)
{
stack_size = size;
stack = (int *)malloc(stack_size * sizeof(int));
if(stack == NULL)
printf("malloc is fail!");
}
void push(int data)
{
if((stack_size -1) >= top_cnt )
{
top_cnt += 1;
stack[top_cnt] = data;
}
else
printf("the stack is full!");
}
void pop(void)
{
if(top_cnt > -1)
top_cnt -= 1;
}
void destroy_stack(void)
{
if(stack != NULL)
{
stack_size = 0;
free(stack);
stack = NULL;
}
}
void stack_printf(void)
{
int i;
i = top_cnt;
if(i == -1)
printf("the stack is empty!\n");
while(i != -1)
{
printf("%d ", stack[i]);
i--;
}
printf("\n");
}
int main(void)
{
create_stack(20);
stack_printf();
push(1);push(2);push(3);push(4);push(5);push(6);push(7);
printf("push data: ");
stack_printf();
printf("\n");
printf("top data is : %d\n", stack[top_cnt]);
pop();
pop();
printf("pop data after :");
stack_printf();
printf("\n");
printf("top data is : %d\n", stack[top_cnt]);
destroy_stack();
return 1;
}
运行效果
七、总结
对于我而言,结合了程序的内存分配来理解,这个更方便理清代码的逻辑,希望各位大佬在评论区批评指正!