The main reason is that it is creating a vector with a random amount of positions, is whatever is in the memory at that moment, and this will burst the memory most of the time, but not at all.
What you probably wanted is to declare the vector after asking how many positions it would be (as I did in the code), then you reserve in memory the space for the quantity typed, no longer take an arbitrary value.
It has nothing to do with the operating system but with the memory junk that you have at that time of execution in the location that was allocated to your application. It may even repeat the same value, but it’s just a coincidence.
This mistake probably has to do with people’s mania to teach C how it was in the 1970s, or how it is in Pascal. So I’m critical of almost every programming course you have out there, they don’t teach you how to program in real life.
The code doesn’t take any precautions yet, but for exercise it’s fine. I have improved the organization to be more readable and more efficient (a loop solves the question, you don’t need to ask for the data and then sweep the entire array to find the desired information).
#include <stdio.h>
#include <limits.h>
int main() {
int n;
scanf("%d", &n);
int x[n];
int menor = INT_MAX;
int posicao = 0;
for (int i = 0; i < n; i++) {
scanf("%d", &x[i]);
if (x[i] < menor) {
menor = x[i];
posicao = i;
}
}
printf("Menor valor: %d Posicao: %d", menor, posicao);
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).
– Maniero