我一直有一个很难搞清楚这段代码:链表开头插入
typedef struct student_grade sg;
sg *first = NULL;
sg *renew = NULL;
sg *temp = NULL;
int num;
float g;
char classname[12], fn[STR_LENS], ln[STR_LENS];
printf("Enter the classname (without spaces): ");
scanf("%11s", classname);
printf ("Enter the student's name and their grade. Enter 0 0 0 to quit. \n(FirstLast ##.#): ");
num = scanf("%11s %11s %f", fn, ln, &g);
while (fn[0] != '0')
{
if (num == 3)
{
renew = (sg*) malloc(sizeof(sg));
strncpy(renew->first_name, fn, STR_LENS-1);
strncpy(renew->last_name, ln, STR_LENS-1);
renew->grade = g;
renew->next = first; //next pointer to first
first = renew; //assign address of renew to first
}
else
{
return 1;
}
printf("Enter the student's name and their grade.Enter 0 0 0 to quit\n(First Last ##.#): ");
num = scanf("%11s %11s %f", fn, ln, &g);
}
特别是这部分:
renew = (sg*) malloc(sizeof(sg));
strncpy(renew->first_name, fn, STR_LENS-1);
strncpy(renew->last_name, ln, STR_LENS-1);
renew->grade = g;
renew->next = first; //next pointer to first
first = renew; //assign address of renew to first
的renew
被分配结构,指向first
指针,它最初是NULL,并且first
被指定了与renew
相同的地址,然后指向地址renew
。在第二次循环之后,同样的renew
显然被克隆,并且也指向first
的地址,然后first
的地址被分配与克隆的renew
相同的地址。
没有一个加起来。