为什么是段错误?
- C/C++ code
#include <stdio.h>#include <stdlib.h> #include <string.h> //为了截取字符串 strncpy struct testimone{ char *nome; int arrivo; int parte; // struct testimone *next; }; typedef struct testimone *Testimone; typedef struct testimone testimone; struct coppia{ testimone prima; testimone dopo; struct coppia *next; }; typedef struct coppia *Coppia; //声明函数 Testimone new_tm(); void incontra(Testimone a,Testimone b); void pd(Coppia *c,testimone a,testimone b); int main(){ Testimone x= new_tm(); Testimone y=new_tm(); incontra(x,y); Coppia *cp; cp=NULL; pd(cp,*x,*y); //printf("%d",x->arrivo); return 0; } Testimone new_tm(){ Testimone tm; char *nom,str[10]; nom=str; int arr,par; // printf("Input nome: "); scanf("%s%d%d",nom,&arr,&par); if((tm=malloc(sizeof(struct testimone)))== NULL){ fprintf(stderr,"Errore: malloc()\n"); exit(1); } (tm->nome)=nom; (tm->arrivo)=arr; (tm->parte)=par; // printf("%s",tm->parte); return tm; } void incontra(Testimone a,Testimone b){ if( ( (a->arrivo)<=(b->parte) ) && ( (a->parte)>=(b->arrivo) ) ) printf("Sono incontrato\n"); else printf("NON sono incontrato\n"); } //一个组组内排序 void pd(Coppia *c,testimone a,testimone b){ Coppia *new; if((new=malloc(sizeof(struct coppia)))== NULL){ fprintf(stderr,"Errore: malloc()\n"); exit(1); } if( (a.parte) < (b.arrivo) ) { (*new)->prima = a; (*new)->dopo = b; } if( (b.parte) < (a.arrivo) ) { (*new)->prima = b; (*new)->dopo = a; } (*new)->next=*c; *c=*new; }
运行输入:
qh@qh-VirtualBox:~$ gcc testimone.c
qh@qh-VirtualBox:~$ ./a.out
qh 11 13
we 14 15
NON sono incontrato
段错误
//我的指针哪里用错了啊,请指正
[解决办法]
- C/C++ code
Testimone x = new_tm(); Testimone y = new_tm();//首先你这个会使得x=y=你最后设置的那个,局部数组或指针返回会出错
[解决办法]
并且也是无效的,new_tm函数中Testimone tm是一个局部变量,在函数执行结束时就会销毁,所以该函数返回的也就是无效的结构体指针
[解决办法]
正解。