Reputation: 87
I'm having problems creating a function that creates two separate linked lists in C.
In my program, the user enters an equation such as 7 + 9 * 8, character by character, the program then makes lists with them.
The code is as follows: (Where place is where is should be in the list and data is the number/operator itself. Both come from another part of the program)
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;
}
}
I identified through a tonne of printf statements that it will add the first number in the equation to the list successfully, how it does not add the first operator and with the second number the program crashes altogether.
The crashing problem appears to occur in the places I have written [CRASH], when I put temp2->next = temp1.
Any help greatly appreciated!
Upvotes: 2
Views: 62
Reputation: 140168
maybe not the only issue but:
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;
is shadowing temp2
declared in the outer scope. So the outer temp2
is never initialized, your initialization sets a value to a variable that goes out of scope.
So remove struct trees *
so the same temp2
variable is used (and initialised), like this (I'd prefer a ternary expression, though):
if((data == '/') || (data == '*') || (data == '+') || (data == '-'))
{
temp2 = operador_uno;
}
else
{
temp2 = numero_uno;
}
And turn on compiler warnings which would have told you that:
temp2
uninitializedtemp2
variablesUpvotes: 3