获取scanf的返回值失败,段错误
当输入的数据错误时scanf返回值为零,正常会不执行循环继续往下执行程序的,但不知道怎么回事会返回段错误。求解。。。
#include <stdio.h>
#include <stdlib.h>
#define ElemType int
typedef struct Lnode
{
ElemType data;
struct Lnode *prior, *next;
}Lnode, *LinkList;
void insert(LinkList L);
void change(LinkList L, int i);
void print(LinkList L);
void insert(LinkList L)
{
ElemType n;
Lnode *p;
_Bool flag = 1;
p = L;
printf("请输入链表数据:\n");
while (flag)
{
flag = scanf("%d", &n);
if (flag)
{
Lnode *new;
new = (Lnode*)malloc(sizeof(Lnode));
if (new == NULL)
{
printf("内存分配失败!\n");
exit(1);
}
new->data = n;
p->next = new;
new->next = NULL;
new->prior = p;
p = new;
}
}
}
void change(LinkList L, int i)
{
Lnode *p, *pre;
p = L->next;
while (i-- && p != NULL)
{
p = p->next;
}
pre = p->prior;
p->prior = pre->prior;
pre->prior->next = p;
pre->next = p->next;
p->next->prior = pre;
p->next = pre;
pre->prior = p;
}
void print(LinkList L)
{
Lnode *p;
p = L->next;
while (p)
{
printf("%d ", p->data);
p = p->next;
}
putchar('\n');
}
int main(void)
{
int p;
LinkList L;
L = (LinkList)malloc(sizeof(Lnode));
if (L == NULL)
{
printf("内存分配失败!\n");
exit(1);
}
L->prior = NULL;
L->next = NULL;
insert(L);
printf("请输入指针位置:");
scanf("%d", &p);
change(L, p);
printf("交换之后的链表:");
print(L);
return 0;
}
本帖最后由 剑魔独孤 于 2021-4-18 21:06 编辑
#include <stdio.h>
#include <stdlib.h>
#define ElemType int
typedef struct Lnode
{
ElemType data;
struct Lnode *prior, *next;
}Lnode, *LinkList;
void insert(LinkList L)
{
ElemType n;
Lnode *p;
_Bool flag = 1;
p = L;
printf("please input a value:\n");
while (flag)
{
flag = scanf("%d", &n);
if (flag)
{
Lnode *new;
new = (Lnode*)malloc(sizeof(Lnode));
if (new == NULL)
{
printf("内存分配失败!\n");
exit(1);
}
new->data = n;
p->next = new;
new->next = NULL;
new->prior = p;
p = new;
}
}
}
void change(LinkList L, int i)
{
Lnode *p, *pre;
p = L->next;
while (i-- && p->next != NULL)
{
p = p->next;
}
pre = p->prior;
p->prior = pre->prior;
pre->prior->next = p;
pre->next = p->next;
p->next = pre;
}
void print(LinkList L)
{
Lnode *p;
p = L->next;
while (p!=NULL)
{
printf("%d ", p->data);
p = p->next;
}
putchar('\n');
}
int main()
{
int p;
LinkList L;
L = (LinkList)malloc(sizeof(Lnode));
if (L == NULL)
{
printf("memory fail\n");
exit(1);
}
L->prior = NULL;
L->next = NULL;
insert(L);
printf("point:\n");
getchar();
scanf("%d",&p);
change(L, p);
printf("swap:\n");
print(L);
return 0;
} 你没写注释,我不知道你是叫交换输入位置处的数与后面的交换还是其他的,,下次记得写注释,一般没有谁、愿意搞一个没有注释的代码 剑魔独孤 发表于 2021-4-18 21:10
你没写注释,我不知道你是叫交换输入位置处的数与后面的交换还是其他的,,下次记得写注释,一般没有谁、愿 ...
主要是代码我试了,不用获取的scanf的返回值可以运行,只有flag = scanf那块有问题,但是我其他的程序用却没问题。所以就想问为什么获取不到scanf返回的0,就没详细写注释 嗯嗯,有返回值呀,不然,我这是怎么调出来呢
页:
[1]