我对C语言没有太多经验。
所以我试图为堆写一个简单的c程序,但它显示了一堆错误。
因此,我可能在数据元素中出错了。
错误日志:
stack.c:31:11: error: unknown type name ‘stack’
void push(stack[],top){
^
stack.c:31:19: error: unknown type name ‘top’
void push(stack[],top){
^
stack.c:45:6: warning: conflicting types for ‘pop’ [enabled by default]
void pop(stack,top){
^
stack.c:19:1: note: previous implicit declaration of ‘pop’ was here
pop();
^
stack.c:54:6: warning: conflicting types for ‘traverse’ [enabled by default]
void traverse(stack,top){
^
stack.c:22:1: note: previous implicit declaration of ‘traverse’ was here
traverse();
^
stack.c: In function ‘traverse’:
stack.c:62:20: error: subscripted value is neither array nor pointer nor vector
printf("%d\n",stack[i]);
程序:
#include <stdio.h>
#include <stdlib.h>
void main(){
int stack[10];
int i;
int choice;
printf("Enter the elementz\n");
for ( i = 0; i < 10; i++){
scanf("%d",&stack[i]);
printf("++++++++ MENU ++++++++\n\n\n");
printf("Enter 1 to push \n Enter 2 to pop\n Enter 3 to display \n\n\n");
printf("Enter you choice \n\n\n");
scanf("%d",&choice);
switch(choice){
case 1 :
push();
break;
case 2:
pop();
break;
case 3 :
traverse();
break;
default:
printf("Enter the correct choice\n");
}
}
}
void push(stack[],top){
int item;
int max = 10;
printf("Enter the number you want to input\n");
scanf("%d",&item);
if(top == stack[max]-1){
printf("It's full\n");
}
else{
top = top+1;
stack[top] = item;
}
}
void pop(stack,top){
if(top == -1){
printf("STack is empty\n");
}
else{
top = top-1;
}
}
void traverse(stack,top){
int i;
if(top == -1){
printf("WHy r u giving m empty stack to print");
}
else{
for (i = 0; i <10; i++){
printf("Your stack is : \n");
printf("%d\n",stack[i]);
}
}
}
提前谢谢。
答案 0 :(得分:1)
traverse()
中的循环条件看起来很奇怪。int main(void)
而不是void main()
,这在C89中是非法的,在C99或更高版本中是实现定义的,除非您有一些使用非标准签名的特殊原因。 试试这个:
#include <stdio.h>
#include <stdlib.h>
void push(int stack[],int* top);
void pop(int stack[],int* top);
void traverse(int stack[],int top);
int main(void){
int stack[10];
int top = 9;
int i;
int choice;
printf("Enter the elementz\n");
for ( i = 0; i < 10; i++){
scanf("%d",&stack[i]);
}
for ( i = 0; i < 10; i++){
printf("++++++++ MENU ++++++++\n\n\n");
printf("Enter 1 to push \n Enter 2 to pop\n Enter 3 to display \n\n\n");
printf("Enter you choice \n\n\n");
scanf("%d",&choice);
switch(choice){
case 1 :
push(stack,&top);
break;
case 2:
pop(stack,&top);
break;
case 3 :
traverse(stack,top);
break;
default:
printf("Enter the correct choice\n");
}
}
}
void push(int stack[],int* top){
int item;
int max = 10;
printf("Enter the number you want to input\n");
scanf("%d",&item);
if(*top == max-1){
printf("It's full\n");
}
else{
*top = *top+1;
stack[*top] = item;
}
}
void pop(int stack[],int* top){
if(*top == -1){
printf("STack is empty\n");
}
else{
*top = *top-1;
}
}
void traverse(int stack[],int top){
int i;
if(top == -1){
printf("WHy r u giving m empty stack to print");
}
else{
for (i = 0; i <= top; i++){
printf("Your stack is : \n");
printf("%d\n",stack[i]);
}
}
}