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

标签 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;
}

最佳答案

此错误消息通常意味着您在空指针上使用了 ->

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

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

关于c - 嵌套结构指针无法访问地址 0x8 处的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41154178/

相关文章:

c - Turbo c 中的默认值

c - 关于 malloc() : writing outside of allocated memory

c - C 中的 UDP 套接字 - 传递整数值

c - 数组传递无效?

ios - 如何转到导致 xcode 错误的行

Git:错误:RPC 失败;结果=22,HTTP 代码=411

c++ - 如果你知道地址,你能访问另一个程序的堆栈/堆吗?

c++ - 为什么以及何时通过指针在 C++ 中传递类类型?

c++ - 如何使用指针从不同的函数访问局部变量?

ios - NSClassFromString 在解包 Optional 值时发现 nil