首页 > 解决方案 > 在 C 中创建链表时程序崩溃

问题描述

我在创建一个在 C 中创建两个单独的链表的函数时遇到问题。

在我的程序中,用户输入一个等式,例如 7 + 9 * 8,一个字符一个字符,然后程序用它们创建列表。

代码如下:(where where is where is should be in list and data 是数字/运算符本身。两者都来自程序的另一部分)

struct trees {

    char data;
    int posicion;
    struct trees *next;
    struct trees *childI;
    struct trees *childD;

};

    struct trees *root;
    struct trees *operador_uno;
    struct trees *numero_uno;

    char *numeros;
    char *operadores;
    int num, num_operadores;


void crearLista(int place, char data) {

    int i;

    struct trees *temp1 = (struct trees *)calloc(1, sizeof(struct trees));

    temp1->data = data;

    if(place == 0) {
        if((data == '/') || (data == '*') || (data == '+') || (data == '-')){
            temp1->next = operador_uno;
            operador_uno = temp1;
        }
        else {
            temp1->next = numero_uno;
            numero_uno = temp1;
        }

    }

    else {

        struct trees *temp2;

        if((data == '/') || (data == '*') || (data == '+') || (data == '-')) {
            struct trees *temp2 = operador_uno;
        }
        else {
            struct trees *temp2 = numero_uno;
        }

        for(i = 0; i < place - 1; i++) {
            temp2 = temp2->next; // [CRASH]
        }

        temp1->next = temp2->next;
        temp2->next = temp1; // [CRASH]

    }


    for(i = 0; i < place && place != 0; i++) {
        struct trees *temp1 = operador_uno;
        temp1 = temp1->next;
    }

    for(i = 0; i < place + 1; i++) {
        struct trees *temp2 = numero_uno;
        temp2 = temp2->next;
    }

}

我通过大量 printf 语句确定它将成功地将等式中的第一个数字添加到列表中,它如何不添加第一个运算符以及第二个数字程序完全崩溃。

当我输入 temp2->next = temp1 时,崩溃问题似乎发生在我写 [CRASH] 的地方。

非常感谢任何帮助!

标签: clistlinked-list

解决方案


也许不是唯一的问题,但是:

    struct trees *temp2;

    if((data == '/') || (data == '*') || (data == '+') || (data == '-')) {
        struct trees *temp2 = operador_uno;  // not the same "temp2" as above
    }
    else {
        struct trees *temp2 = numero_uno;  // not the same "temp2" as above
    }

    for(i = 0; i < place - 1; i++) {
        temp2 = temp2->next; // [CRASH] because temp2 isn't initialized
    }

struct trees *temp2 = operador_uno;是在外部范围中声明的阴影。 temp2因此,外部temp2永远不会初始化,您的初始化会为超出范围的变量设置一个值。

所以删除struct trees *所以使用相同的temp2变量(并初始化),就像这样(我更喜欢三元表达式,不过):

 if((data == '/') || (data == '*') || (data == '+') || (data == '-')) 
 {
    temp2 = operador_uno;
 }
else 
 {
    temp2 = numero_uno;
 }

打开编译器警告,它会告诉你:

  • 您正在使用外部temp2未初始化
  • 你没有使用内部temp2变量

推荐阅读