Home > other >  Why arr[i][j-1] = zero?
Why arr[i][j-1] = zero?

Time:03-21

Why is the arr[i][j-1] zero? After testing using the printf function, it shows that the position is arr[0][-1] and it has the value 0 as it appears from the results below.

int main() {
int arr [2][4];
int i,j;



for (i=0; i<2; i  ) {
    for (j = 0; j < 4; j  ) {
        printf("Provide a number: ");
        scanf("%d", &arr[i][j]); // get the values
        printf("The arr[i][j] is %d\n",arr[i][j]);
        printf("The arr[i][j-1] is %d\n",arr[i][j-1]);             
    }
}
//print the values
for (i=0; i<2; i  ) {
    for (j = 0; j < 4; j  ) {
        printf("%d\n",arr[i][j]);
}
}
}

Example of how it works:

Provide a number: 12
The arr[i][j] is 12
The arr[i][j-1] is 0
Provide a number: 14
The arr[i][j] is 14
The arr[i][j-1] is 12
Provide a number:

If the following arr[i][j-2] is used though, then it shows this:

The arr[i][j-2] is 6611520

this is typical in C but the 0 in j-1 is not clear. Can you explain?

CodePudding user response:

arr[0][-1] is outside the bounds of the array.

Reading or writing outside the bounds of an array (or even creating a pointer to such an element) triggers undefined behavior. Loosely speaking, this means there are no guarantees regarding what your program will do.

  • Related