-3

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.

4 Answers4

0

If you want to have 5 elements for both arrays:

Change the declarations of s and t to s[5] and t[5]. Only at the declaration the 5 means 5 elements. Only at indexing and addressing a certain element, counting starts at 0, not 1.


If you want to have the arrays to be consisted of 4 elements:

for (i = 0; i <= 4; i++)

i <= 4 - With this condition and the initialization i = 0 you access memory beyond the bounds of the array at the last iteration, which invokes undefined behavior.

When i == 4, s[i] and t[i] is an out of bounds access as s and t are both arrays of 4 int, not 5.

It needs to be i < 4 or i <= 3 for the arrays of 4 int or (if you want to) or change the initialization to i = 1.

0

Delete the equals in the for loops:

for (i = 0; i < 4; i++)

The length of the arrays is 4. From 0 to 4 (included) there are 5 positions.

When you declare int s[4]; you create an arrays of lenght 4: s[0], s[1], s[2], s[3]. You can't access s[4].

This is because the position starts to 0.

0

for (i=0; i <4; i++)

in your code you access 5 elements of the array and your array has only 4 elements. It ans Undefined Behaviour.

Second loop the same error.

0___________
  • 60,014
  • 4
  • 34
  • 74
0

There is a problem with the size of the array, you need to modify your code of that line to given code:

int i, s[4], t[4], u=0;

to

int i, s[5], t[5], u=0;
Ashish Karn
  • 1,127
  • 1
  • 9
  • 20