[英]I'm trying to create a stack in c using structures but my push function doesn't work
我正在尝试使用结构在 C 中创建堆栈,但我编写的push()
function 行为异常。 我确定我很明显缺少了一些东西,但我只是想不通是什么。
#include <stdio.h>
#define STACK_SIZE 50
typedef struct stack
{
int top;
int items[STACK_SIZE];
}
STACK;
void push(STACK* st, int newitem)
{
st->top++;
st->items[st->top] = newitem;
printf("%d", st->items[st->top]);
}
int main()
{
int n = 1;
STACK* st;
printf("test 1\n");
st->top = -1;
push(st, n);
printf("test 2\n");
return 0;
}
DevCpp 只编译但不执行代码。 OnlineGDB 运行它但只打印第一个测试。
这是因为你的变量STACK* st;
从未正确初始化。
-1
分配给长度 ( top
), 0
会更好STACK* st;
应该只是STACK st;
void push(STACK* st, int newitem)
应使用static
链接声明。st->top++
st
变量传递给push()
functionreturn 0;
, 使用return EXIT_SUCCESS;
,它在 header 文件stdlib.h
中定义。STACK_SIZE
只有50
,因此int
就足够了。 但是随着您的STACK_SIZE
增长,请使用size_t
作为您的长度( top
)。int main(void) { }
,而不是int main() { }
STACK_SIZE
和top
变得相等意味着您的array
已完全填充,那么进一步添加数据将导致Undefined Behavior 。#include <stdio.h>
#include <stdlib.h>
#define STACK_SIZE 50
typedef struct stack
{
int top;
int items[STACK_SIZE];
}
STACK;
static void push(STACK* st, int newitem)
{
if(st->top == STACK_SIZE)
{
fprintf(stderr, "stack size reached maximum length\n");
exit(EXIT_FAILURE);
}
st->items[st->top++] = newitem;
printf("%d\n", st->items[st->top - 1]); // we added +1 to `top` in the above line
}
int main(void)
{
int n = 1;
STACK st;
printf("test 1\n");
st.top = 0;
push(&st, n); //pass by address
return EXIT_SUCCESS;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.