【问题标题】:C - Cannot get stack to initiate in my programC - 无法在我的程序中启动堆栈
【发布时间】:2019-02-05 02:10:55
【问题描述】:

我正在尝试创建一个堆栈,但我在启动它时遇到了问题。我的代码是:

#define LINELN 72    
#define STACKSZ 25    
#define NEWLN '\n'    
#include <stdlib.h>    
#include <stdio.h>  

// interface struct for stack
typedef struct stack {    
  char data[STACKSZ];    
  int top;    
} stack;    

void initstk(stack *s1);    
int emptystk(stack s);    

int main() {
  stack s1;
  initstk(s1);
  printf("%d",emptystk(s1)); 
  exit(0);
}

void initstk(stack *s1) {
  s1->top=-1;
}

int emptystk(stack s) {
  if(s.top == -1){
    return 1;
  }
  else{
    return 0;
  }
}    

我希望它打印出 1,因为堆栈是空的,但它仍然打印出 0。我真的不明白。会不会是指针的原因?

【问题讨论】:

标签: c arrays struct stack typedef


【解决方案1】:

您声明:

void initstk(stack *s1);
/*...*/
int main() {
stack s1;

但是你调用为:

initstk(s1);

因为initstk带有指针参数,所以应该传递s1的地址:

initstk(&s1);

我很惊讶你的编译器没有警告你不匹配。

【讨论】:

    猜你喜欢
    • 2023-03-24
    • 1970-01-01
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-11
    • 2021-03-03
    相关资源
    最近更新 更多