一个C链表问题

来源:百度知道 编辑:UC知道 时间:2024/06/01 21:00:52
#include <stdio.h>
#include <malloc.h>
struct pbook
{
char *name;
int xuehao;
};
typedef struct pbook node;
void main()
{
char *name="opasfds";
int xuehao=4855;
node *head;
head=(node *)malloc(sizeof(node));
head->name=name;
head->xuehao=xuehao;
printf("%s\n%d",head->name,head->xuehao);
free(head);
}
这个用VC6.0编译运行成功。。达到目的。
下面这个,代码没有完全给出。只给了一个函数,错误就在这个函数里面。
#include "stdio.h"
#include "malloc.h"
struct pbook
{
char *name;
int xuehao;
struct pbook *next;
};
typedef struct pbook node;
void print_linklist(node *head)
{
int i;
node *p;
p=head;
for(i=1;p->next!=NULL;i++)
{
p=p->next;
printf("编号:%d\n姓名:%s\n学号:%d\n",i,p->name,p->xuehao);
printf("***************

不会是指针的问题,我把你上面的合成下面的程序

#include "stdio.h"
#include "malloc.h"
struct pbook
{
char *name;
int xuehao;
struct pbook *next;
};
typedef struct pbook node;
void print_linklist(node *head)
{
int i;
node *p;
p=head;
for(i=1;p!=NULL;i++) //////如果你只有一个节点的,p->next!=NULL; 会导致无数据输出
{

printf("编号:%d\n姓名:%s\n学号:%d\n",i,p->name,p->xuehao);
printf("***************************************\n");
p=p->next;
}
}

void main()
{
char *name="opasfds";
int xuehao=4855;
node *head;
head=(node *)malloc(sizeof(node));
head->name=name;
head->xuehao=xuehao;
print_linklist(head) ;
free(head);
}

问题在这里:
for(i=1;p->next!=NULL;i++)
{
p=p->next; //有问题

你在for循环中是先判断p->next != NULL, 但是 又执行了 p = p->next,
当 for循