I was studying this subject in C, and in most places I'm looking for, one of the examples of using this feature is when you're going to create a vector whose size you do not know. Example:
int main() {
int num = 0, i = 0, *vetor;
printf("Digite a quantidade de números que deseja armazenar: \n");
scanf("%d", &num);
vetor = (int *) malloc(sizeof(int) * num);
for(; i < num; i++) {
printf("Digite um valor inteiro para o %dº elemento do vetor: \n", i);
scanf("%d", &vetor[i]);
}
for (i = 0; i < num; i++) {
printf("O %dº elemento do vetor é: %d\n", i, vetor[i]);
}
free(vetor);
return 0;
}
But, I can rewrite the program as follows, without using dynamic allocation, and it will continue to work:
int main() {
int num, i = 0;
printf("Digite a quantidade de números que deseja armazenar:\n");
scanf("%d", &num);
int vetor[num];
for (; i < num; i++) {
printf("Digite um valor inteiro para o %dº elemento do vetor: \n", i);
scanf("%d", &vetor[i]);
}
for (i = 0; i < num; i++) {
printf("O %dº elemento do vetor é: %d\n", i, vetor[i]);
}
return 0;
}
What is the difference that dynamic allocation makes in this case? Is there a situation where you have no alternative but to allocate dynamically? And what would be the difference between these two?
vetor = (int *) malloc(sizeof(int) * num);
vetor = malloc(sizeof(int) * num);