Your code does not allocate as you imagine, you are making a serious mistake. This code is far from doing what you think it is.
You’re reserving memory for vet with an undetermined amount of elements. Yes, because you declared tam but did not put any value to it. So the value that is in the memory position of tam will be the size of vet. Certainly the information that is there is garbage. It may be that it is zero and does not reserve memory for vet. It may be a very large number and reserve several KB or MB of memory without you needing it.
You only get one value for tam after the variable vet is declared.
What you may not have understood is that C lets you do whatever you want with memory. If it works by coincidence, poor your application. In C you have to make sure everything is working properly. Taking a test and thinking it’s working is a danger. It worked in a specific situation. The next execution may not work, the execution on another computer may not work. Although this is especially important in C, it is something that applies to any language. Testing and working does not guarantee that the program is correct, especially in C where there is much undefined behavior (answer here). Unfortunately there is widespread thinking that thinks a simple test is enough.
A possible correct implementation:
#include <stdio.h>
int main(void) {
int tam;
printf("\ndigite tam: ");
scanf("%d", &tam);
int vet[tam];
printf("%d", vet[0]);
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Note that I am just doing what you intended. I am not storing anything in this array.
See a example on Wikipedia how to allocate in stack.
Then the
C99allows you to declare variables in how much the program runs ?C99would be higher than theC90andC89– ViniciusArruda
Voce is not declaring variables while the program runs, Voce is determining the size of the array that is already declared and will be created at execution time.
– Lucas Virgili
C99does not allow variable declaration at runtime. It allows the size of a vector to be determined at runtime.– Vinícius Gobbo A. de Oliveira
@Lucasvirgili worth complementing that as
tamwas not initialized at the time of variable declarationvet, we have aundefined behaviorin this code. Compiling with the flag-Wallgcc must display the unchecked variable Warning.– Vinícius Gobbo A. de Oliveira
ah yes, I ignored his code to answer the question. in fact the vector has indefinite size.
– Lucas Virgili