69,371
社区成员
发帖
与我相关
我的任务
分享
node->next = head;
head = node;
struct type{
char name[32];
struct type *next;
};
struct type* head;
void create_list()
{
char name[32]={0};
struct type *p = NULL,*q = NULL;
int i = 0;
while(i<5){
p =(struct type*)malloc(sizeof(struct type*));
printf("input the data\n");
scanf("%s",name);
strcpy(p->name, name);
p->name[30]='\0';
//p->next = NULL;
if(i==0)
head = p;
else
q->next =p;
q = p;
i++;
}
}
为什么这样的链表建好之后,打印的时候老是报段错误,如果把字符数组改成int就没事struct AnyNode
{
char type[10];
void* data;
AnyNode* next;
};
void ListInsert(AnyNode** head, void* data, char* type)
{
AnyNode* node = (AnyNode*)malloc( sizeof(AnyNode) );
node->next = NULL;
node->data = NULL;
memset(node->type, 0, 10);
strcpy(node->type, type);
if ( strcmp(type, "int")==0 )
{
node->data = (int*)malloc(sizeof(int));
*( (int*)node->data ) = *( (int*)data );
}
else if ( strcmp(type, "char")==0 )
{
node->data = (char*)malloc(sizeof(char));
*( (char*)node->data ) = *( (char*)data );
}
node->next = *head;
*head = node;
}
void ListPrint(AnyNode* head)
{
while (head)
{
if ( strcmp(head->type, "int")==0 )
{
printf("%d ,", *( (int*)head->data ));
}
else if ( strcmp(head->type, "char")==0 )
{
printf("%c ,", *( (char*)head->data ));
}
head = head->next;
}
printf("\n");
}
AnyNode* head = NULL;
int ii = 4;
ListInsert(&head, &ii, "int");
char ch = 'a';
ListInsert(&head, &ch, "char");
ListPrint(head);