动态链表的建立于输出问题
//建立一个链表存放学生的信息struct student
{
char *name;
char sex;
int age;
struct student * next;
};
//建立动态链表
struct student *create()
{
struct student *head,*p1,*p2;
int n = 0;
p1 = p2 = (struct student*)malloc(sizeof(struct student));
ZeroMemory(p1,sizeof(struct student));
head = NULL;
scanf("%s",p1->name);
scanf("%c",&p1->sex);
scanf("%d",&p1->age);
while(p1->name != NULL)
{
n = n +1;
if(n == 1)head = p1;
else p2->next = p1;
p2 = p1;
p1 =(struct student*)malloc(sizeof(struct student));
scanf("%s",p1->name);
scanf("%c",&p1->sex);
scanf("%d",&p1->age);
}
p2->next = NULL;
return head;
}
int main(int argc, char* argv[])
{
struct student *pt;
printf("请输入姓名、性别(M\F)、年龄:\n");
pt = create();
while(pt != NULL)
{
printf("%s\t%c\t%d",pt->name,pt->sex,pt->age);
pt = pt->next;
}
system("pause");
return 0;
}请问大神这是怎么回事?
结构体里姓名定义是一个没用的指针!!野指针…… char *name = NULL; :lol:
灰常感谢大神救助:lol: // test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdlib.h>
#include <windows.h>
//建立一个链表存放学生的信息
struct student
{
char name;
char sex;
int age;
struct student * next;
};
//建立动态链表
struct student *create()
{
struct student *head,*p1,*p2;
int n = 0;
p1 = p2 = (struct student*)malloc(sizeof(struct student));
ZeroMemory(p1,sizeof(struct student));
head = NULL;
scanf("%s %c %d",p1->name,&p1->sex,&p1->age);
while(strcmp(p1->name,"end") != 0)
{
n = n +1;
if(n == 1)
{
head = p1;
printf("access done!\n");
}
else p2->next = p1;
p2 = p1;
p1 =(struct student*)malloc(sizeof(struct student));
ZeroMemory(p1,sizeof(struct student));
scanf("%s %c %d",p1->name,&p1->sex,&p1->age);
printf("access done!\n");
}
p2->next = NULL;
return head;
}
int main(int argc, char* argv[])
{
struct student *pt;
printf("请输入姓名、性别(M\F)、年龄:\n");
pt = create();
if(pt != NULL)
printf("姓名\t性别\t年龄\n");
while(pt != NULL)
{
printf("%s\t%c\t%d\n",pt->name,pt->sex,pt->age);
pt = pt->next;
}
system("pause");
return 0;
}
附上完整代码 在对指针进行操作的时候,不管指针在结构体内还是在别处,都要先分配内存才可以使用
页:
[1]