Help with this problem in C

3

I leave here the code of a vector that I have made but I have no idea why it does not do what it should.

I have put a variable called cantidad , and a vector[cantidad] so that the user can manage the values of the array but only puts up to 6 values.

For example: How many values do you want in the array ?: 7, then enter up to 6 ..

#include <stdio.h>

int main()
{
    printf("ARRAY VARIABLE\n\n");

    int cantidad;
    int vector[cantidad];

    printf("Introduzca la cantidad de valores del array: ");
    scanf("%d",&cantidad);

    for(int i=0;i<cantidad;i++)
    {
        printf("%d valor del array: ",i+1);
        scanf("%d",&vector[i]);
    }

    printf("\nValores introducidos\n\n");   
    for(int i=0;i<cantidad;i++)
    {
        printf("  %d",vector[i]);
    }

    return 0;
}
    
asked by Mario Guiber 24.07.2017 в 17:55
source

1 answer

6
int cantidad;
int vector[cantidad];

Notice that in those two lines of code ... you are defining the vector. and the size. But you are never defining how much is worth. And what you define later, does not solve the problem, because vector is already dimensioned. Therefore, you must define vector, after knowing how much quantity is worth. And it lets you enter 6 or 7 or 9 miraculously.

that is ... your code should go like this:

printf("Introduzca la cantidad de valores del array: ");
scanf("%d",&cantidad);
int vector[cantidad];
    
answered by 24.07.2017 / 18:00
source