编译通过,运行又是段错误!!请高手指导下一般该怎么解决
又是段错误!!请高手指导下一般段错误该怎么解决程序如下,就是创建一个动态链表..自己写了库函数叫list.h 主函数list.c 在gcc下编译通过,运行是段错误.
我将2个程序放一起写在下面了,顺便打包..
list.rar
(1.25 KB)
#ifndef _LIST_H_
#define _LIST_H_
#include<stdio.h>
#include<stdlib.h>
#define OFFSIDE(TYPE,ELEMENT) (&(((TYPE*)0)->ELEMENT))
#define BASE_ADD(TYPE,ELEMENT,ADDR) (ADDR - OFFSIDE(TYPE,ELEMENT))
typedef struct node node_t;
struct node
{
int date;
node_t *next;
};
typedef struct stu stu_t;
struct stu
{
int id;
char name[20];
int age;
char sex;
node_t tag;
};
typedef struct tch tch_t;
struct tch
{
int id;
char name[20];
char lesson[20];
int age;
char sex;
node_t tag;
};
typedef struct list list_t;
struct list
{
int size;
node_t *head;
};
void init(list_t *lt)
{
lt->head = NULL;
lt->size = 0;
}
void add(list_t *lt,node_t *nd)
{
node_t *index = lt->head;
if(lt->head == NULL)
lt->head = nd;
else{
while(index->next){
index = index->next;}
index->next = nd;
}
}
void ergod(list_t *lt,void (*f)(node_t *nd))
{
node_t *index = lt->head;
while(index){
f(index);
index = index->next;
}
}
void print_stu(node_t *nd)
{
stu_t *stp = (stu_t *)BASE_ADD(stu_t,tag,nd);
printf("stu:%6d %10s %6d %c\n",stp->id,stp->name,stp->age,stp->sex);
}
void print_tch(node_t *nd)
{
tch_t *tp = (tch_t *)BASE_ADD(tch_t,tag,nd);
printf("stu:%6d %10s %10s %6d %c\n",tp->id,tp->name,tp->lesson,tp->age,tp->sex);
}
#endif
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"list.h"
int main()
{
list_t lt,lt_tch;
init(<);
init(<_tch);
int i;
for(i=0;i<20;i++)
{
stu_t *stp = (stu_t*)malloc(sizeof(stu_t));
stp->id = i + 1;
sprintf(stp->name,"NB%d",i+1);
stp->age = i*10;
stp->sex = 'm';
stp->tag.date = i;
stp->tag.next = NULL;
add(<,&(stp->tag));
tch_t *tp = (tch_t*)malloc(sizeof(tch_t));
tp->id = i + 1;
sprintf(tp->name,"NB %d",i+1);
sprintf(tp->lesson,"work %d",i);
tp->age = i*10;
tp->sex = 'm';
tp->tag.date = i;
tp->tag.next = NULL;
add(<_tch,&(tp->tag));
ergod(<,print_stu);
printf("*************************");
printf("*************************");
printf("*************************");
printf("*************************");
ergod(<_tch,print_tch);
}
return 0;
}