How to define the vector size dynamically in C?

Asked

Viewed 7,902 times

5

In language C I can define a vector specifying the size for example int vet[3]; how can I set the size of vector dynamically, for example by asking the user to inform the size of the vector ?

  • You intend to use this vector as?

2 answers

5

To allocate a vector dynamically you must use the function malloc or calloc. You must know how to operate pointers to understand briefly how it works.

For example, to allocate a vector with 10 integer positions:

int *vetor = malloc(sizeof(int) * 10);

The same thing can be done with the function calloc thus:

int *vetor = calloc (10,sizeof(int))

You can change the value 10 for some variable you read from the user previously.

The access to vector positions is done in the same way as if it were a statically allocated vector: vetor[0], vetor[1] and so on.

If you need to change the vector size at runtime (dynamically), you can use the function realloc, for example, to increase the size of the vector allocated to 20:

vetor = realloc(vetor, 20 * sizeof(int));

Don’t forget to include the library <stdlib.h> containing the dynamic allocation functions.

Important: This allocated space will no longer be released unless you explicitly release with the command free(vetor). If you forget to dislocate and lose the reference to the vector pointer, your program will have wasted memory that you will no longer be able to recover. This happens to dynamically allocated memory.

Modern operating systems displace your program’s memory (including the one that was lost) after running it, even if you forget to manually relocate.

  • Thank you so much for the explanation, it was of great help to me.

4


You basically have two forms:

  1. use of malloc() and friends
  2. use of VLA, from C99

Using malloc() and friends you can change the size of the array whenever you need it; using VLA size is fixed after set.

Using VLA the array is actually an array while with malloc() and friends what you have is a pointer to a memory area.

Example with malloc() and friends

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int *pa = NULL;
    size_t sa = 0;
    for (;;) {
        printf("Enter size: ");
        fflush(stdout);
        if (scanf("%zu", &sa) != 1) break;
        pa = malloc(sa * sizeof *pa);
        if (pa == NULL) {
            fprintf(stderr, "erro na alocacao\n");
            exit(EXIT_FAILURE);
        }
        // usa pa
        // desde pa[0] ate pa[sa - 1]
        free(pa);
    }
}

Example with VLA

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    size_t sa = 0;
    for (;;) {
        printf("Enter size: ");
        fflush(stdout);
        if (scanf("%zu", &sa) != 1) break;
        int arr[sa];
        // usa arr
        // desde arr[0] ate arr[sa - 1]
    }
}
  • Thank you very much for the explanation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.