我一直很难搞清楚这段代码:

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指针,first被分配到renew的相同地址,然后指向renew的地址。在第二个循环之后,同一个renew显然被克隆,并指向first的地址,然后first的地址被分配给克隆的renew的相同地址。
这些都不算。

最佳答案

没有克隆发生。每次迭代都会分配一个新的内存块(这就是renew调用所做的),并更改malloc指针以引用这个新内存。

10-08 02:00