翁恺C语言程序设计入门 链表课的两个问题(写在代码里)


typedef struct _node {
    int value;
    struct _node* next;
}Node;
 
int main(int argc, char* argv[])
{
    Node* head = (Node*)malloc(sizeof(Node));
    int number;
    do {
        scanf("%d", &number);
        if (number != -1) {
         Node* p = (Node*)malloc(sizeof(Node));
         p->value = number;
         p->next = NULL;
         Node* last = head;
         if( last ){
           while (last->next) {//问题1:引发了未经处理的异常:读取访问权限冲突。 last 是 0xCDCDCDCD。
            last = last->next;//问题2:左边的last会得到右边last->next的什么?是地址吗?是last->next所指向的地址吗?
            printf("hellow");
           }
          last->next = p;
         }
         else {
             head = p;
         }
        }
    } while (number != -1);
}

修改如下,见注释,供参考:

#include <stdio.h>
#include <malloc.h>
typedef struct _node {
    int   value;
    struct _node* next;
}Node;

int main(int argc, char* argv[])
{
    Node* head = (Node*)malloc(sizeof(Node));
    head->next = NULL;   //问题1:头结点的 next 指针没有初始化,是个随机值,所以在输入第一结点值时 last->next != NULL 
    int number;          //条件满足,造成误判断。
    do {
        scanf("%d", &number);
        if (number != -1) {
            Node* p = (Node*)malloc(sizeof(Node));
            p->value = number;
            p->next = NULL;
            Node* last = head; 
            if (last) {
                while (last->next) {//问题1:引发了未经处理的异常:读取访问权限冲突。 last0xCDCDCDCDlast = last->next;//问题2:左边的last会得到右边last->next的什么?是地址吗?是last->next所指向的地址吗?
                    printf("hellow\n");//问题2:理解正确。
                }
                last->next = p;
            }
            else {
                head = p;
            }
        }
    } while (number != -1);
}

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

typedef struct _node
{
    int value;
    struct _node *next;
} Node;

int main(int argc, char *argv[])
{
    Node *head = (Node *)malloc(sizeof(Node));
    int number;
    do
    {
        scanf("%d", &number);
        if (number != -1)
        {
            Node *p = (Node *)malloc(sizeof(Node));
            p->value = number;
            p->next = NULL;
            Node *last = head;
            while (last->next)
            {
                last = last->next;
            }
            last->next = p;
            printf("hellow");
        }
    } while (number != -1);

    Node *p = head->next;
    while (p)
    {
        printf("%d ", p->value);
        p = p->next;
    }
    printf("\n");

    return 0;
}

img