pEnd=pNew=(struct Student*)malloc(sizeof(struct Student));这句看不懂,求大神解释,详细具体点,急!

#include<stdio.h>
#include<stdlib.h>

struct Student
{
char cName[20]; /*姓名*/
int iNumber; /*学号*/
struct Student* pNext; /*指向下一个结点的指针*/
};

int iCount; /*全局变量表示链表长度*/

struct Student* Create()
{
struct Student* pHead=NULL; /*初始化链表头指针为空*/
struct Student* pEnd,*pNew;
iCount=0; /*初始化链表长度*/
pEnd=pNew=(struct Student*)malloc(sizeof(struct Student));
printf("please first enter Name ,then Number\n");
scanf("%s",&pNew->cName);
scanf("%d",&pNew->iNumber);
while(pNew->iNumber!=0)
{
iCount++;
if(iCount==1)
{
pNew->pNext=pHead; /*使得指向为空*/
pEnd=pNew; /*跟踪新加入的结点*/
pHead=pNew; /*头指针指向首结点*/
}
else
{
pNew->pNext=NULL; /*新结点的指针为空*/
pEnd->pNext=pNew; /*原来的为节点指向新结点*/
pEnd=pNew; /*pEnd指向新结点*/
}
pNew=(struct Student*)malloc(sizeof(struct Student)); /*再次分配结点内存空间*/
scanf("%s",&pNew->cName);
scanf("%d",&pNew->iNumber);
}
free(pNew); /*释放没有用到的空间*/
return pHead;
}

void Print(struct Student* pHead)
{
struct Student *pTemp; /*循环所用的临时指针*/
int iIndex=1; /*表示链表中结点的序号*/

printf("----the List has %d members:----\n",iCount); /*消息提示*/
printf("\n"); /*换行*/
pTemp=pHead; /*指针得到首结点的地址*/

while(pTemp!=NULL)
{
printf("the NO%d member is:\n",iIndex);
printf("the name is: %s\n",pTemp->cName); /*输出姓名*/
printf("the number is: %d\n",pTemp->iNumber); /*输出学号*/
printf("\n"); /*输出换行*/
pTemp=pTemp->pNext; /*移动临时指针到下一个结点*/
iIndex++; /*进行自加运算*/
}
}

int main()
{
struct Student* pHead; /*定义头结点*/
pHead=Create(); /*创建结点*/
Print(pHead); /*输出链表*/
return 0; /*程序结束*/
}

您好。
C语言中,连续赋值是从右到左进行的,于是您看不懂的那行可以理解为如下两行代码:
pNew = (struct Student *)malloc(sizeof(struct Student));
pEnd = pNew;
从等号最右分析:
(struct Student *)malloc(sizeof(struct Student))
malloc函数的作用是申请内存空间,参数是想申请的空间的大小,它将返回一个可以 强制转换为任何类型的,指向申请好的内存空间 的指针。
sizeof操作符(注意它不是函数)可以取得操作数所占用的内存空间的大小。这里的操作数是Student结构体

所以这句代码的执行顺序为:
1.获取Student结构体所需的内存空间大小;
2.向系统申请第1步获得的大小的内存空间,并取得指向这个空间的指针;
3.将指向这个空间的指针强制转化为一个Student结构体类型的指针;
4.将这个指针赋值给pNew;
5.将pNew赋值给pEnd。
温馨提示:答案为网友推荐,仅供参考
相似回答