I am trying to understand how array boundaries work in C, so tried the following code:
#include <stdio.h>
int main(){
{
int i, s[4], t[4], u=0;
// fisrt loop
for (i=0; i<=4; i++)
{
s[i] =i;
t[i] =i;
printf("s = %d\n", s[i]);
printf("t = %d\n", t[i]);
}
// second loop
printf("s:t\n");
for (i=0; i<=4; i++)
printf("%d:%d\n", s[i], t[i]);
printf("u = %d\n", u);
}
return 0;
}
The output is as follows :
fisrt loop
s = 0
t = 0
s = 1
t = 1
s = 2
t = 2
s = 3
t = 3
s = 4
t = 4
second loop
s:t
4:0
1:1
2:2
3:3
4:4
u = 0
I am expecting both loops to print 5 elements from 0 to 4. As you can see, the first for loop's output looks ok, but in the second loop the value of s[0] is wrong and for some reason turned to 4. I am assuming that this is happening because of some problem in the array boundary, but I am not sure, please correct me if I am wrong. Is there any way to fix this, and make s[0] correct value? Cheers.