Why does the first element of the vector come out as zero without having stored this value there?

Asked

Viewed 97 times

5

Why the following code prints a 0 at the beginning of the output?

#include <stdio.h>
#include <limits.h>
// Escreva  um  programa    que leia    do  teclado 8   valores,    e   em  seguida os  
// imprima  em  ordem   inversa.


void main()
{
    int numero[8] = {1,2,3,4,5,6,7,8};
    int i = 0;

    printf("\nA distribuicao desses numeros em ordem inversa : ");

    for(i=8;i>=0;i--){
        printf("\n--------\n%d",numero[i]);
    }

}

Exit:

A distribuição desses números em ordem inversa:
--------
0
--------
8
--------
7
--------
6
--------
5
--------
4
--------
3
--------
2
--------
1
--------------------------------
Process exited after 0.1034 seconds with return value 11
Pressione qualquer tecla para continuar. . .

3 answers

6


Do an analysis of what the code performs. When you program you have to understand what the computer will do, understand all the code.

Actually in this case it doesn’t take much, just look at the result. Count how many numbers were printed. Nine, right? But the array There’s only eight elements, so one of the numbers he took out trash in his memory and printed it out. C’s like, he does what you say, it’s your problem to make sure he’s got the right thing in his memory.

In case you’re having element number 8 printed first, but it only goes up to the 7. I know you must think it’s strange, but think about it. Without has 8 elements and one of them is 0, as you did, the last is 7 and not 8. The same thing when we put all the digits individually, we put from 0 to 9, totaling 10 different numbers.

So if you started from 7 everything would be fine. In a correct way, more organized, readable and without what is unnecessary:

#include <stdio.h>

int main() {
    int numero[8] = {1, 2, 3, 4, 5, 6, 7, 8};
    printf("\nA distribuicao desses numeros em ordem inversa : ");
    for (int i = 7; i >= 0; i--) printf("\n--------\n%d", numero[i]);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

1

In C the vectors start from 0 and end in n-1 so your loop should be for(i=8;i>0;i--) or for(i=7;i>=0;i--). In your code you are reading a memory outside because you are printing 9 elements in an array of 8 elements.

-1

That line is with an index more. That is 9 elements.

for(i=8;i>=0;i--){
    printf("\n--------\n%d",numero[i]);
}

The right thing would be.

for(i=8;i>0;i--){
    printf("\n--------\n%d",numero[i]);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.