C语言全局数组和malloc分别做栈
1.两者区别
1.1 内存分配方式
全局数组是在程序编译时就分配好静态内存,它的大小在编译时确定,不会在运行时改变。
malloc函数是在程序运行时动态分配内存,可以根据需要动态调整内存大小。
1.2 内存管理
全局数组由编译器自动处理,无需手动释放。
malloc()需要调用free()动态释放内存
1.3 内存访问
全局数组:内存连续分配,可以通过数组下标直接访问元素,访问速度较快。
malloc():内存通过指针访问,需要使用指针操作来访问内存中的数据,较慢。
1.4 可用空间
全局数组的大小在编译时确定,受到编译器和操作系统限制,如全局数组过大,可能会导致栈溢出或编译不通过。
malloc():可动态分配内存。如果频繁使用malloc(),可能导致内存碎片化。
2.C代码实现
2.1全局数组
#include <stdio.h>
#define MAX_SIZE 100
int stack[MAX_SIZE];
int top = -1;
void push(int value){
if(top >= MAX_SIZE - 1){
printf("stack overflow\n");
return;
}
stack[++top] = value;
}
int pop(){
if(top < 0){
printf("stack underflow\n");
return -1;
}
return stack[top--];
}
int main(){
push(1);
push(2);
push(3);
printf("%d\n", pop());
printf("%d\n", pop());
printf("%d\n", pop());
return 0;
}
2.2 malloc()
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int* stackx;
int top;
int sizex;
}Stack;
Stack* createStack(int size){
Stack* stack = (Stack *)malloc(sizeof(Stack));
stack -> stackx = (int *)malloc(size * sizeof(int));
stack -> top = -1;
stack -> sizex = size;
return stack;
}
void push(Stack* stack, int value){
if(stack -> top >= stack -> sizex - 1){
printf("stack overflow\n");
return;
}
stack -> stackx[++stack->top] = value;
}
int pop(Stack* stack){
if(stack -> top < 0){
printf("stack underflow\n");
return -1;
}
return stack -> stackx[stack -> top--];
}
void destroyStack(Stack* stack){
free(stack -> stackx);
free(stack);
}
int main(){
Stack* mystack = createStack(100);
push(mystack, 1);
push(mystack, 2);
push(mystack, 3);
printf("%d", pop(mystack));
printf("%d", pop(mystack));
printf("%d", pop(mystack));
destroyStack(mystack);
return 0;
}