In C language, is it possible to create a vector, of any type, so that its size is variable? If possible, how?
In C language, is it possible to create a vector, of any type, so that its size is variable? If possible, how?
Once you have declared the vector, do not.
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 block of memory with n * tamanho de um inteiro
size. This is just a vector in C.
After that, you can use a function called realloc
to keep changing the size, but I do not know if that's what you intended.
In C ++, there are vectors of the same dynamic size, the% s of% s.
I think this is what you want, basically when you define a size in the declaration first as the vector, you can 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;
}
I'm still learning, if you detect any error, please tell me.