程序运行到strcmp函数部分异常终止
程序要解决的问题在 https://pta. (因为我发现复制粘贴过来的话,排版不好看,也太长,所以直接贴网址。)我写的程序代码如下:
程序代码:#include <stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node *Node;
struct node {
char Name[11];
int space;
int Parant;
};
Node Tree;
int n;
int Scan(char*);
int Trace(int);
int judgeParent(int,int);//父子
int judgeSibling(int,int);//兄弟
int judgeAncestor(int,int);//祖先
void work();
int Index(char*);
int main() {
int m;
scanf("%d%d",&n,&m);
Node Tree=(Node)malloc(sizeof(struct node)*n);
getchar();//清除缓存
for(int i=0; i<n; i++) {
Tree[i].space=Scan(Tree[i].Name);
Tree[i].Parant=i;
}
Tree[0].Parant=-1;
for(int i=0; i<m; i++) {
work();getchar();
}
return 0;
}
int judgeParent(int x,int y){
if(Tree[x].Parant==x)Tree[x].Parant=Trace(x);
return Tree[x].Parant==y;
}
int judgeSibling(int x,int y){
return Tree[x].space==Tree[y].space;
}
int judgeAncestor(int x,int y){
while(x!=-1){
if(judgeParent(x,y))return 1;
else x=Tree[x].Parant;
}
return 0;
}
void work(){
char StrX[11],StrY[11],relation[11];
scanf("%s%*s%*s%s%*s%s",StrX,relation,StrY);
printf("%s - %s - %s\n",StrX,relation,StrY);
int X=Index(StrX);
int Y=Index(StrY);
printf("%d - %d",X,Y);
int result;
switch(relation[0]){
case 'c':result=judgeParent(X,Y);break;
case 'p':result=judgeParent(Y,X);break;
case 's':result=judgeSibling(X,Y);break;
case 'd':result=judgeAncestor(X,Y);break;
case 'a':result=judgeAncestor(Y,X);break;
default:result=-1;break;
}
if(result==1)printf("True\n");else if(!result)printf("False\n");
else printf("ERROR:系统不能识别所指定关系!\n");
}
int Index(char*a){
for(int i=0;i<n;i++){
printf("*");
if(strcmp(Tree[i].Name,a)==0)return i;
}
printf("ERROR:所给人名不存在!\n");
return -1;
}
int Trace(int child){//往前遍历第一个比他缩进少的就是他的父亲
while(child>0&&(Tree[child-1].space==Tree[child].space))child--;
return child-1;
}
int Scan(char*p) {
char c;
int space=0;
while((c=getchar())==' ')space++;//记录字符串前面的空格数量
do {
*p++=c;
} while((c=getchar())!='\n');
*p='\0';
return space;
}
从插入的 标记性输出 来看,程序是第一次运行到第88行的时候异常终止的。Index函数的作用是根据字符串查找到该人名在数组中的位置。
以往遇到异常终止的时候通常都是不小心跑了无限循环。但是这回的话明显不是循环问题。因为出问题的for循环才执行一次,我猜测应该是strcmp部分的问题。
但是Tree[i].Name和char*a我再三查看过,看不出来这两个参数有什么问题。。。
希望大家不吝赐教,除了循环,还有什么情况下会导致程序异常终止?









