So I was experimenting with arrays in C and came across this weird event where the value of an array changes even though I am not manipulating the data of the elements in that array.
Here is my code:
#include <stdio.h>
#include <conio.h>
int main () {
int arr[] = {0};
scanf("%i", &arr[0]);
scanf("%i", &arr[1]);
for (int i = 0; i < 2; i++) {
printf("value of i %i\n", i);
printf("%i\n", arr[i]);
}
getch();
}
and the output was:
2 //this is an input
3 //this is an input
value of i 0
2
value of i 1
1
I have the same code in Turbo C but in Turbo C the value of the elements in that array is correct, the output in Turbo is is:
2 //this is an input
3 //this is an input
value of i 0
2
value of i 1
3
I tried to debug and see when does the change of value happens in the code, so I tried:
#include <stdio.h>
#include <conio.h>
int main () {
int arr[] = {0};
scanf("%i", &arr[0]);
scanf("%i", &arr[1]);
for (int i = 0; i < 2; i++) {
printf("value of i %i\n", i);
printf("%i\n", arr[i]);
}
printf("%i\n", arr[0]);
printf("%i\n", arr[1]);
getch();
}
and now the output is very weird:
2 //this is an input
3 //this is an input
value of i 0
2
value of i 1
1
2
2
arr[1]is not initialised. Try,int arr[] = {0, 0};