简体   繁体   English

无法将元素插入链表

[英]unable to insert element into linked list

I am trying to write a program that finds all the ")" in an expression and puts them in a linked list, always adding at the beginning of the list. 我试图编写一个在表达式中查找所有")"并将其放入链接列表的程序,始终将其添加到列表的开头。 The problem is that when I try to place a new element into the list, the program stops working. 问题是,当我尝试将新元素放入列表时,程序停止工作。

With a sample user input 865)987 : 使用样本用户输入865)987

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

typedef struct element {
    char data;
    struct element *next;
} ELEMENT;


int main(void)
{
   ELEMENT *first = NULL;
   ELEMENT *new_a;

   char input[30];
   int x=0;

   printf("Input expression: ");
   scanf("%s", &input);

   while(input[x]!='\0'){
       if (input[x]==')'){
           printf("%c", input[x]);        //This works just fine.
           new_a->data = input[x];        //Here, the program stops working.
           new_a->next = first;
           first = new_a;
       }
       x++;
    }
}

What am I doing wrong? 我究竟做错了什么?

new_a->data

is equivalent to 相当于

(*new_a).data

As you can see, new_a is attempted to be dereferenced. 如您所见,尝试将new_a取消引用。 The problem is that new_a is uninitialized , so any subsequent attempt to dereference it is undefined behavior (in shape of, eg, a segmentation fault). 问题在于new_a 未初始化 ,因此任何随后对其进行取消引用的尝试都是未定义的行为 (例如,分段错误的形式)。

In order to fix this, you need to allocate memory for new_a : 为了解决这个问题,您需要为new_a分配内存:

  1. Allocate space on the stack. 在堆栈上分配空间。 This will only work if the linked list is exclusively used in main because local variables' scope only embraces the beginning and end of a function . 这仅在链表仅在main使用时才有效,因为局部变量的作用域仅包含函数的开头和结尾
    Do it like this: 像这样做:

     ELEMENT new_a; ... new_a.data = input[x]; new_a.next = first; first = &new_a; 
  2. Use malloc . 使用malloc This is usually used for linked lists and is applicable for a linked list existing till the very termination of your program because it's scope-independent: 这通常用于链接列表,适用于在程序终止之前一直存在的链接列表,因为它与范围无关:

     ELEMENT* new_a = malloc(sizeof(ELEMENT)); 

    Don't forget to free afterwards! 不要忘了以后free


Notes: 笔记:

您需要为new_a分配内存:

new_a = malloc(sizeof(ELEMENT));

As previously answered, the correct code is: 如前所述,正确的代码是:

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

typedef struct element {
    char data;
    struct element *next;
} ELEMENT;

int main(void)
{
    ELEMENT *first = NULL;  
    char input[30];
    int x=0;

    printf("Input expression: ");
    scanf("%s", &input);

    while(input[x]!='\0'){
        if (input[x]==')'){
            ELEMENT *new_a = (ELEMENT*)malloc(sizeof(ELEMENT));
            printf("%c", input[x]);
            new_a->data = input[x];
            new_a->next = first;
            first = new_a;
        }
        x++;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM