Visual Studio 2019 vector error

Asked

Viewed 53 times

0

Good evening, someone can tell me why this message appears in the program in c language, and if it has how to solve? Run-Time Check Failure #2 - Stack Around the variable 'note' was corrupted. Float ta note[3] why vector starts counting 0 then it would have to be right with 4 numbers.

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

main() {

    float nota[3];

    nota[0] = 8.5;
    nota[1] = 7.5;
    nota[2] = 10;
    nota[3] = 10;

    printf("A primeira nota = %.2f\n", nota[0]);
    printf("A segunda nota = %.2f\n", nota[1]);
    printf("A terceira nota = %.2f\n", nota[2]);
    printf("A quarta nota = %.2f\n", nota[3]);

    system("pause");
    return 0;
}
  • 2

    "'Cause that vector starts with a zero so you’d have to be right with four numbers." In fact you indicate that it will have 3 indexes, as the first index is 0, it ends in note[2]

  • If you want to have 4 notes you have to declare as float nota[4];. The number in the declaration is the size and not the last position.

1 answer

0

Barbetta, I know this is a little confusing for C, but let’s look at it. In the statement of the float vector of note you put how many you want, if you want 4 notes, then you make note[4], all right up there? Now to access the vector index or to go through using a for, for example, you always do (vector size - 1). Soon your code would be:

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

main() {

   float nota[4];

   nota[0] = 8.5;
   nota[1] = 7.5;
   nota[2] = 10;
   nota[3] = 10;

   printf("A primeira nota = %.2f\n", nota[0]);
   printf("A segunda nota = %.2f\n", nota[1]);
   printf("A terceira nota = %.2f\n", nota[2]);
   printf("A quarta nota = %.2f\n", nota[3]);

   scanf("%[^\n]");

   return 0;

}

Ah! Something else, don’t use system("pause") to hold the prompt screen, this is unnecessary, the prompt at the end of the program is always waiting, now if you want to make this explicit, use the function that is in the code above.

Browser other questions tagged

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