1. 程式人生 > >C語言建立連結串列malloc的使用(C的建立物件)

C語言建立連結串列malloc的使用(C的建立物件)

struct student *creat()
{
	struct student *head;
	struct student *p1, *p2;

	p1 = p2 = (struct student *)malloc(LEN);	//LEN是student結構的大小 這就是new物件

	printf("Please enter the num :");
	scanf("%d", &p1->num);
	printf("Please enter the score :");
	scanf("%f", &p1->score);

	head = NULL;
	n = 0;

	while(0 != p1->num)
	{
		n++;
		if(1 == n)
		{
			head = p1;
		}
		else
		{
			p2->next = p1;
		}
		p2 = p1;

		p1 =  (struct student *)malloc(LEN);


		printf("Please enter the num :");
		scanf("%d", &p1->num);
		printf("Please enter the score :");
		scanf("%f", &p1->score);
	}
	p2->next = NULL;
	return head;
}
#include <malloc.h>
#include <stdlib.h>
記得這些標頭檔案