能通过可是不能运行的链表(tc通过,可是VC不行)
// qwqweqw.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct student)
int N=1;
struct student
{
int num;
int score;
struct student *next;
};
struct student *creat(void)
{
struct student *head, *p1, *p2;
p1=p2=(struct student *)malloc(LEN);
head=p1;
printf("the %d one:\n",N);
scanf("%d%d",&p1->num, p1->score);
while(p1->num!=0)
{
N++;
p2->next=p1;
p2=p1;
p1=(struct student *)malloc(LEN);
printf("the %d one:\n",N);
scanf("%d%d",&p1->num, p1->score);
}
p2->next=NULL;
free(p1);
free(p2);
p1=p2=NULL;
return head;
}
void print(struct student *head)
{
struct student *p;
p=head;
for(;p!=NULL;)
{
printf("%d\t%d\n",p->num,p->score);
p=p->next;
}
}
int main(int argc, char* argv[])
{
struct student *p;
p=creat();
print(p);
return 0;
}
[解决办法]
p1=p2=(struct student *)malloc(LEN);
改为 p1=p2=(struct student *)malloc(sizeof(student ));
scanf("%d%d",&p1->num, p1->score);
改为
scanf("%d%d",&p1->num, &p1->score);
其余没看,自己搞定
lz,不学会调试程序是不行的
[解决办法]
// qwqweqw.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct student)
int N=1;
struct student
{
int num;
int score;
struct student *next;
};
struct student *creat(void)
{
struct student *head, *p1, *p2;
p1=p2=(struct student *)malloc(LEN);
head=p1;
printf("the %d one:\n",N);
scanf("%d%d",&p1->num, p1->score);
//while(p1->num!=0)
while(head->num!=0)
{
N++;
p2->next=p1;
p2=p1;
p1=(struct student *)malloc(LEN);
printf("the %d one:\n",N);
scanf("%d%d",&p1->num, p1->score);
}
p2->next=NULL;
//free(p1);
//free(p2);
p1=p2=NULL;
return head;
}
void print(struct student *head)
{
struct student *p;
p=head;
for(;p!=NULL;)
{
printf("%d\t%d\n",p->num,p->score);
p=p->next;
}
}
int main(int argc, char* argv[])
{
struct student *p;
p=creat();
print(p);
return 0;
}