【问题标题】:Program crashing when creating linked lists in C在 C 中创建链表时程序崩溃
【发布时间】:2019-01-09 13:23:09
【问题描述】:

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

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

代码如下:(where place is where is应该在列表中,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 语句确定它将成功地将等式中的第一个 number 添加到列表中,它如何不添加第一个 operator 以及第二个数字程序完全崩溃。

当我把 temp2->next = temp1.

非常感谢任何帮助!

【问题讨论】:

  • 学习使用 gdb 将是给自己的一份很棒的礼物,因为它可以节省查找故障位置的时间。

标签: c list linked-list


【解决方案1】:

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

    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; 是在外部范围内声明的 shadowing temp2。所以外部的temp2 永远不会被初始化,你的初始化会为一个超出范围的变量设置一个值。

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

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

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

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

【讨论】:

  • 请注意,至少使用 gcc,您可以打开 -Wshadow 以查看有关阴影的警告,然后您会收到比您提到的警告更多的警告。
猜你喜欢
  • 2015-06-09
  • 2019-10-01
  • 2017-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-29
  • 1970-01-01
  • 2021-02-11
相关资源
最近更新 更多