我一直有一個很難搞清楚這段代碼:鏈表開頭插入
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
相同的地址。
沒有一個加起來。