嵌套结构指针不能访问地址0x8处的内存

时间:2016-12-14 23:47:54

标签: c pointers runtime-error text-editor doubly-linked-list

我正在尝试使用学校项目的链接列表来创建基本文本编辑器。当我试图从键盘程序中取一个字母时,会导致运行时错误。我看了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;
}

1 个答案:

答案 0 :(得分:0)

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

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

也许不是headLine = lastLine = currentLine;,而是headLine = lastLine = currentLine = link;?                     – M.M