我在创建一个在 C 中创建两个单独的链接列表的函数时遇到问题。
在我的程序中,用户输入一个等式,例如 7 + 9 * 8,逐个字符,然后程序用它们制作列表。
代码如下:(where place 是列表中应该出现的位置,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
变量
关于c - 在C中创建链表时程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51642310/