How to create a vector of variable size?

Asked

Viewed 40,473 times

17

In C language, it is possible to create a vector of any type so that its size is variable? If possible, how to do?

2 answers

25


Once you have declared the vector, no.

However, you can make the vector have different size depending on the user input.

For example, if we want the user to enter a value for the vector size, we can do something like:

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

int main() {
    int n;
    int *v;
    int i;
    printf("Entre com o tamanho do vetor: ");
    scanf("%d", &n);
    v = (int *)malloc(n * sizeof(int));
    for (i = 0; i < n; ++i) {
         v[i] = i;
    }
    for (i = 0; i < n; ++i) {
        printf("%d ", v[i];)
    }
    printf("\n");
    free(v);
    return 0;
}

What we do is declare a pointer to integers and say that this variable will point to a memory block with size n * tamanho de um inteiro. That’s just a vector in C.

After that, you can use a function called realloc to keep changing the size, but I don’t know if it was what you intended.

Already in C++ there are vectors of even dynamic size, the vectors.

  • 1

    Thank you Lucas Virgili! I tested and it worked! Thank you very much! However, I was left with one more question, what is the cast (int *) in this case? Because I pulled this cast to see if it worked and worked the same way... on this show, what is its function?

  • 1

    Voce can accept the answer then :)

  • 4

    The cast for int * is optional because in C type pointers void *, like the one returned by malloc, they are automatically converted to other types (similarly to automatic coercion between the various numerical types). Writing the cast explicitly or letting it occur automatically is a matter of style. Other than that in C++ this automatic coercion does not exist and then you need the cast even (although in C++ is not usually used malloc)

  • Thank you very much hugomg! Now I understand! Did not know this information... thank you very much Lucas Virgili and hugonmg!

-1

I think this is what you want, basically by setting a size in the declaration before the vector, you will be able to change that size as follows.

 int main()
    {

    int tamanho=10, vec[tamanho], i=0;

    //Aqui alteramos o tamanho do vector ao mudar o valor da variável tamanho

    printf("Introduza o tamanho do vector: ");

    scanf("%d", &tamanho);

    for(i=0; i<tamanho; i++){
        printf("Preencha o vector: ");
        scanf("%d", &vec[i]);
        }

    for(i=0; i<tamanho; i++){

    printf("%d", vec[i]);
    printf("\n");
    }

    system("PAUSE");
    return 0;

    }

Obs: I’m still in the learning phase, if you find any errors, let me know.

Browser other questions tagged

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