Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why arr[i][j-1] = zero?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading