How to ask the user to enter the size of the vector?

-1

I'm only using vectors with a defined number using the define or even direct on the variable. How do I put the amount of vectors the user chooses?.

example:

    #define NUMERO x

    int main()
    {
    int valor[NUMERO];

I want this x to be a number that the user can type (choose) at the beginning of the program.

    
asked by anonymous 12.09.2018 / 15:47

1 answer

0
int main(){
    int x=10;
    int valor[x];
}

It's the same thing to do

int main(){
    int valor[10];
}

Or using define

// #define x ValorPredefinido 
#define x 10 /** EXEMPLO, caso saiba que será esse valor **/ 

int main(){
    int valor[x];
}

From the codes below we do not know the amount that will be needed at the start.

int main(){
    int x;
    printf("Qual o tamanho do vetor?"); 
    scanf("%d", &x); /** caso seja um valor que o usuário terá de colocar**/
    int valor[x];
}

Another option is to use dynamic memory.

int main(){
  int *valor;
}

Go allocating memory as you need more space.

  • What you can not do is int valor[x] without having a value, in the examples above when it reaches this line x will have a value
12.09.2018 / 16:01