yxlovemoney 发表于 2007-6-2 04:21:43

运行的问题

程序如下

#include<stdio.h>
#define NULL 0
#define LEN sizeof(struct student)
struct student
{
    long num;
    float pay;
    struct student *next;
};
int n;
struct student *creat()
{
    struct student *head;
    struct student *p1,*p2;
    n=0;
    p1=p2=(struct student *)malloc(LEN);
    scanf("%ld,%f",&p1->num,&p1->pay);
    head=NULL;
    while(p1->num!=0)
    {
      n=n+1;
      if(n==1) head=p1;
      else
            p2->next=p1;
      p2=p1;
      p1=(struct student *)malloc(LEN);
      scanf("%ld,%f",&p1->num,&p1->pay);
    }
    p2->next=NULL;
    return(head);
}
void list(struct student *head)
{
    struct student *p;
    printf("\n now .the %d records are:\n",n);
    p=head;
    if(head!=NULL)
      do{
            printf("%ld %f\n",p->num,p->pay);
            p=p->next;

      
      }while(p!=NULL);
}
main()
{
    struct student *head;
    printf("input records:\n");
    head=creat();
    list(head);
}



为什么这程序在C++里可运行,但在C里不能呢?在C里只能执行一次,然后就提示错为
“scanf:floating pointformats   not   linked   Abnormalprogram   termination”
怎么会这样呢?


还有就是开始的那几句
p1=p2=(struct student *)malloc(LEN);
    scanf("%ld,%f",&p1->num,&p1->pay);
    head=NULL;
    while(p1->num!=0)
    {
      n=n+1;
      if(n==1) head=p1;
      else
            p2->next=p1;
      p2=p1;
      p1=(struct student *)malloc(LEN);
      scanf("%ld,%f",&p1->num,&p1->pay);
    }
    p2->next=NULL;
    return(head);
应该如何理解呢?

Zelsazgh 发表于 2007-6-2 06:04:40

第一个问题尚未测试估计是由于你在while中时由于重复分配内存的原因.....
第二个问题该函数实现了链表结构....head代表链表的头....
while循环的工作是添加链表数据....p2最后的指向表示了链表结尾.....
页: [1]
查看完整版本: 运行的问题