【发布时间】:2018-12-28 04:59:27
【问题描述】:
我在我的代码上做的一切都是正确的,但仍然有一个我不知道为什么的问题
#include<stdio.h>
#include<stdlib.h>
struct node {
int data ;
struct node* link ;
};
struct node* top = NULL ;
void pop(){
if(top==NULL)
printf("element that will delete is %d\n",top->data);
else {
struct node* temp ;
temp= top ;
top = top->link ;
temp->link = NULL ;
free(temp);
}}
void push() {
struct node* temp ;
temp =(struct node*) malloc(sizeof(struct node ));
printf("please enter the data of the first node \n");
scanf("%d",&temp->data);
temp->link = top ;
temp = top ;
}
void printx(){
if(top==NULL)
printf("there is no element to print\n");
else {
struct node* temp ;
while(temp != NULL) {
printf("%d\n",temp->data) ;
temp = temp->link ;
}
}
}
int main() {
printf("please enter the type of operation u want to perform\n") ;
printf("enter 1 for push , 2 for pop , 3 for print: ") ;
int x ;
scanf("%d",x) ;
switch(x){
case 1 :
printf("\nu choosed push\n");
push();
break ;
case 2 :
printf("u choosed pop \n");
pop() ;
break ;
case 3 :
printf("u choosed to print the element of the stack\n") ;
printx();
break ;
}
}
【问题讨论】:
-
寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。
-
在流行音乐中你有这个代码:
if(top==NULL) printf("element that will delete is %d\n",top->data);。取消引用 NULL 指针肯定会崩溃。 -
没有编译器错误?肯定是关于
scanf("%d", x);的警告吗?这应该是scanf("%d", &x); -
感谢您的认可。
-
@bruceg 不,不是。这是未定义的行为,这意味着。无法保证会发生什么。在 CP/M 下用 BDS C 编译它,当你取消引用 NULL 指针时它绝对不会崩溃。