Your code does not allocate as you think, you are making a serious mistake. This code is far from doing what you think it is.
You are reserving memory for vet
with undetermined amount of elements. Yes, because you declared tam
but did not put any value to it. Then the value that is in the memory location of tam
will be the size of vet
. Certainly the information that is there is crap. It may be zero and do 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 a value for tam
after the vet
variable is declared.
What you may not have understood is that C lets you do what you want with memory. If it works by coincidence, poor of its application. In C you have to make sure everything is working properly. Taking a test and finding that it is working is a danger. It worked in a specific situation. The next run may not work, running on another computer may not work. Although this is especially important in C, it is something that holds true for any language. Testing and working does not guarantee that the program is correct , especially in C where there is a lot undefined behavior . Unfortunately there is a widespread thought 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]);
}
See running on ideone . And in Coding Ground . Also I put it in GitHub for future reference .
Notice that I'm just doing what you intended. I'm not storing anything in this array .
See a example on Wikipedia how to allocate in stack . p>