0
#include<stdio.h>

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>(TOP)
#include<fstream.h>

#define MAX 5

int top = -1;
int stack_arr[MAX];

main()
{
int choice;
while(1)
{
printf("1.Push\n");
printf("2.Pop\n");
printf("3.Display\n");
printf("4.Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1 :
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Wrong choice\n");
}/*End of switch*/
}/*End of while*/
}/*End of main()*/

push()
{
int pushed_item;
if(top == (MAX-1))
printf("Stack Overflow\n");
else
{
printf("Enter the item to be pushed in stack : ");
scanf("%d",&pushed_item);
top=top+1;
stack_arr[top] = pushed_item;
}
}/*End of push()*/

pop()
{
if(top == -1)
printf("Stack Underflow\n");
else
{
printf("Popped element is : %d\n",stack_arr[top]);
top=top-1;
}
}/*End of pop()*/

display()
{
int i;
if(top == -1)
printf("Stack is empty\n");
else
{
printf("Stack elements :\n");
for(i = top; i >=0; i--)
printf("%d\n", stack_arr[i] );
}
}/*End of display()*/
4

3 回答 3

2

您应该在 main 之前声明这些函数:

void push();
void pop();
void display();

或将实际声明移到 main 之上。

于 2010-04-14T16:31:24.780 回答
0

void push();在主要之前添加

于 2010-04-14T16:33:03.077 回答
0

如果您告诉我们您使用的是什么编译器以及它给您的确切错误消息,那将非常有帮助。如果您稍微格式化您的代码也会有所帮助(尽管这个特定的片段很小且足够简单易读)。

所以,这里发生了几件事。首先是,如果您没有显式键入函数定义,则假定该函数返回int(即该函数是隐式键入的int)。因此,mainpushpopdisplay都假定返回int。这是一种非常过时且令人不快的风格,并且 IINM 在 C99 标准中是被禁止的。由于pushpopdisplay不向调用者返回值,它们应该被显式键入voidmain应该明确输入int(在底部进一步讨论)。

其次,如果编译器在看到函数调用之前没有看到函数声明或定义,那么它将假定函数返回int。如果您稍后使用不同的返回类型定义函数,这可能会导致类型不匹配错误,如下所示:

int main(void)
{
  ...
  foo();
  ...
}

void foo(void) { ... }

当编译器看到对 in 的调用foo()main(),它假设foo()将返回一个int,但后来的定义与该假设相矛盾,因此它发出诊断。

这里的教训是,您至少应该在调用函数之前声明它们,如下所示:

int main(void)
{
  void push();
  void pop();
  void display();
  ...
  push();
  ...
  pop();
  ...
  display();
  ...
}

void push(void) { ... }
void pop(void) { ... }
void display(void) { ... }

并确保声明定义匹配。就个人而言,我遵循“使用前定义”规则,如下所示:

void push(void) { ... }
void pop(void) { ... }
void display(void) { ... }

int main(void)
{
  ...
  push();
  ...
  pop();
  ...
  display();
}

这样您就不必担心保持声明和定义同步。

关于 的定义main: C 标准正好为 定义了两个接口main

int main(void); 
int main(int argc, char *argv[]); 

单独的实现可以为 ;定义额外的接口main;几个添加第三个参数,如下所示:

int main(int argc, char *argv[], char *env[]);

Your definition of main must conform to one of the two forms specified in the standard, or one of the forms specified in the documentation for your particular compiler, or the behavior of the program will be undefined (which can mean anything from running as expected, crashing immediately, or running to completion but leaving the system in a bad state, or something else completely). There are several authors who insist that if you don't need the return value from main() you can type it void, but that's only true if the compiler documentation explicitly says that it supports void main().

于 2010-04-14T18:05:18.290 回答