嵌套结构指针无法访问地址为 0x8 的内存

Nested structure pointer cannot access memory at address 0x8

我正在尝试为学校项目做一个带有链接列表的基本文本编辑器。当我试图从键盘程序中获取一封信时,程序崩溃导致运行时错误。我用调试器观察了 currentLine->headLetter,它处于 void insertLetter 函数中,它说无法访问地址 0x8 处的内存。我不明白为什么它会崩溃?

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

struct sentence {
    struct sentence *next;
    struct sentence *prev;
    char letter;
};

struct sentence *currentLetter;

struct line{
    struct line *next;
    struct line *prev;
    struct sentence *headLetter;
    struct sentence *lastLetter;
};

struct line *headLine;
struct line *lastLine;
struct line *currentLine;

void gotoxy(int x, int y)
{
  static HANDLE h = NULL;
  if(!h)
    h = GetStdHandle(STD_OUTPUT_HANDLE);
  COORD c = { x, y };
  SetConsoleCursorPosition(h,c);
}

void insertFirstLine ()
{
   struct line *link = (struct line*) malloc(sizeof(struct line));

   headLine = lastLine = currentLine;
   headLine = link;
   link->prev = NULL;
   link->next = NULL;
}

void insertLetter (char data)
{
    struct sentence *link = (struct sentence*) malloc(sizeof(struct sentence));
    link->letter = data;

        currentLine->headLetter = link;
        currentLine->lastLetter = link;
        currentLetter = link;
        link->next = NULL;
        link->prev = NULL;

}

void newFile ()
{
    char control;
    while (1)
    {
        control = _getch();
        insertLetter(control);
    }
}

int main ()
{
    insertFirstLine();
    newFile();
    return 0;
}

此错误消息通常表示您在空指针上使用了 ->

currentLine->headLetter = link;中,currentLine是一个空指针。

也许您指的是 headLine = lastLine = currentLine = link; 而不是 headLine = lastLine = currentLine;? – M.M