简体   繁体   中英

Invalid int in scanf and printf

I recently started learning the C language programming and now I was doing this simple program where I was supposed to ask the user for 5 numbers and display them on the opposite order. I managed to do it just fine but there's a huge problem. The first number is ridiculous. I can't really explain it so I'll leave an image to show it:

img

And here's the Code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void main()
{
    int numeros[5];
    int i;

    for (i=0; i<5; i++) {
        scanf("%i", &numeros[i]);
    }
    for (i=5; i>0; i--) {
        printf("%i \n", numeros[i]);
    }

    system("pause");
}

Arrays start from index 0 and goes till n-1. So you have defined you array as numeros[5], so your n = 5. Hence your array start from 0 goes till 5-1=4.

The number that you get (negative number in screen shot) is a garbage value and may/may not differ from run to run and from machine to machine as you are trying to access numeros[5].

Hence you need to change your for loop from

for (i=5; i>0; i--){

to

for (i=4; i>=0; i--){

Your second loop must be

for (i=4; i>=0; i--)

instead of

for (i=5; i>0; i--)

As they start with 0 and end with length-1

They can be depicted as.

在此处输入图片说明

Thus the value you are trying to read is out of the array and is thus garbage

The second loop counts 5,4,3,2,1. Since numeros has 5 elements, the 6th element ( numeros[5] ) does not exist and therefore you get a weird number (which is techincally undefined behavior ).

A simple fix is to count down from 4 to 0 instead:

for (i=4; i>=0; i--){
  printf("%i \n", numeros[i]);
}

This is because the last index of you array is always the length of the array - 1, since, as everybody knows, in C, arrays start from 0.

In your case, the length of your array is 5, so the last index is 4. In your loop, you are trying to loop starting from the position 5, therefore you are accessing something that does not belong to the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM