I'm making a program that has global arrays. In the function where I assign values to the arrays and print them, everything is fine. But as soon as I try to use these arrays in another function, suddenly the values are different.
int *numeros;
char *operadores;
int num, num_operadores;
void crearArray() {
int i;
printf("How many numbers?\n");
scanf("%d", &num);
numeros = (int*)calloc(num, sizeof(int));
operadores = (char*)calloc(num - 1, sizeof(char));
num_operadores = num - 1;
num += (num - 1);
for (i = 0; i < num; i++) {
if(i % 2 == 0 || i == 0) {
printf("\t\nEnter a number: ");
scanf("%d", &numeros[i]);
}
else {
fflush(stdin);
printf("\t\nEnter an operator: ");
scanf("%c", &operadores[i]);
}
}
printf("Array: ");
for (i = 0; i < num; i++) {
if(i % 2 == 0 || i == 0)
printf("%d ", numeros[i]);
else
printf("%c ", operadores[i]);
}
}
void crearArbol() {
int i;
printf("\n\nArrays:\n\t Numbers: ");
for(i = 0; i < num_operadores + 1; i++)
printf("\n\t\t Numeros[%d]: %d ", i, numeros[i]);
printf("\n\t Operators: ");
for(i = 0; i < num_operadores; i++)
printf("\n\t\t Operadores[%d]: %c ", i, operadores[i]);
}
int main() {
crearArray();
crearArbol();
return 0;
}
Of course, printing the array wasn't the main purpose for crearArbol but for now there's nothing in there but that and I can't seem to work out why it changes.
Example output:
How many numbers?
3
Enter a number: 1
Enter an operator: *
Enter a number: 2
Enter an operator: /
Enter a number: 3
Array: 1 * 2 / 3 (Printed array from first function crearArray)
Arrays: Numbers:
Numeros[0]: 1
Numeros[1]: 0
Numeros[2]: 2
Operators:
Operadores[0]:
Operadores[1]: * (Printed array values from second function crearArbol)
Thanks in advance for any help!