Dynamic memory allocation X vector

4

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);
    
asked by anonymous 26.03.2016 / 03:44

1 answer

4

The so-called dynamic allocation is done in the heap . This has implications for the lifetime of the object . We are at this location, it survives the end of the function, it does not overflow or overload the application stack and gives more control until it is available.

In general it is always possible to allocate dynamically, it is just not desirable, it has several problems that can be seen in the links posted here. This is a choice that should be made with parsimony, only when it really is needed and brings advantages.

In this specific example there is a reason to use dynamic allocation: It may be too large. When the size is unknown by the programmer it should go the safest way. And in this specific case the dynamic allocation does not bring real disadvantages (I do not know if it would say the same if the example changes, even if little). It will not give problems in the normal tests that someone would do with few elements, but with 1 million would probably give. Already 1 billion might give the dynamic allocation error as well.

See more:

26.03.2016 / 04:06