7
I was studying this subject in C, and in most of the places I look for, one of the examples of using this resource is when you’re going to create a vector whose size you don’t 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 difference does dynamic allocation make in this case? Is there any situation where you have no alternative but to dynamically allocate? And what would be the difference between those two?
vetor = (int *) malloc(sizeof(int) * num);
vetor = malloc(sizeof(int) * num);
No need to do malloc Typecast.
– gato
Actually it’s practically a mistake to do this in C. But it’s one of those things that people will never learn because it’s full of example teaching wrong.
– Maniero
Even better that
apontador = malloc(elementos * sizeof (tipo))
isapontador = malloc(elementos * sizeof *apontador)
because you don’t need to check if the type matches the defined type.– pmg