[英]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
分配内存:
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;
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));
Notes: 笔记:
input
to scanf
suffices; input
传递给scanf
就足够了; no need for &input
. &input
。 Your scanf
is vulnerable to buffer overflows. 您的
scanf
容易受到缓冲区溢出的影响。 Use 采用
scanf("%s29", input);
您需要为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.