c - 在 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] 的地方。
非常感谢任何帮助!
解决方案
也许不是唯一的问题,但是:
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
变量
推荐阅读
- java - 在列表中创建具有不同大小的列表 - 主列表中包含子列表和子列表
- java - Lombok 导入和@XXX 在 Eclipse 中的 Java 中不起作用
- php - 从 URL Apache 中删除 .php
- php - php Carbon 设置输入区域设置
- python - 如何在python中替换列表中的单引号
- javascript - Javascript - 从资产文件夹中的文件实例化新文件类型
- linux - 列出并更改目录并在 Shell 中运行命令
- javascript - javascript获取调用函数的参数?
- android - 像素 2 模拟器/虚拟设备不在 AVD 管理器设备列表中
- php - 我们如何在 php 中获取 .ai 文件的尺寸