Why does the first element of the vector go out as zero without having saved that value there?

5

Why does the following code print a 0 at the beginning of 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]);
    }

}

Output:

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. . .
    
asked by anonymous 12.10.2018 / 23:20

3 answers

6

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

Actually in this case do not need much, just look at the result. Count how many numbers were printed. Nine, right? But the array only has 8 elements, so one of the numbers it took garbage into memory and printed. C is like this, it does what you say, it's your problem to ensure you have the right thing in memory.

In case you are ordering element number 8 first, but it only goes to number 7. I know you must be finding it strange, but think about it. There are 8 elements and one of them is 0, as you did, the last one is 7 and not 8. The same thing when we put all the numbers individually, we put 0 to 9, totaling 10 different numbers.

So if it started from 7 everything would work out. Correctly, 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]);
}

See running on ideone . And no Coding Ground . Also I put it in GitHub for future reference .

    
12.10.2018 / 23:31
1

In C the vectors start from 0 and end at n-1 then their 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 a vector of 8 elements.

    
12.10.2018 / 23:35
-1

This line has one more index. That is 9 elements.

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

The correct one would be.

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