My C code compiles but is not executed

Asked

Viewed 48 times

-1

The code is as follows::

#include <stdio.h>

int main(void) {
    int qtdDeElementos;
    int vetor[qtdDeElementos];

    printf("Informe a quantidade de elementos do vetor: ");
    scanf("%i", &qtdDeElementos);
    
    return 0;
}

The vector that I have declared does not yet have any role in my program because it is not yet complete. I wrote this little excerpt and decided to compile and run to test if everything was right so far. Turns out it only compiles, but it doesn’t run. I have tested other codes and they are all compiled and executed as expected.

Important note: the above code works normally if I remove the vector statement.

Obs2: I’m using extensions to run the code by Vscode, but I’ve tried cmd and the problem persists.

  • 1

    You are creating your vector, and reserving an amount of memory for it before reading the qtdDeElementos. So I’m sure he’ll be raised the wrong size.

1 answer

2


The problem is that you declared the vector without a preset value. First you should read the value of the variable "qtdDelements" and then declare the vector.

Follow the example (I put the 'for' loop to fill and print the vector spaces):

#include <stdio.h>

int main(void) {

    const int qtdDeElementos;

    printf("Informe a quantidade de elementos do vetor: ");
    scanf("%i", &qtdDeElementos);

    int vetor[qtdDeElementos];

    for(int i = 0; i<qtdDeElementos; i++)
    {
        vetor[i] = i;
        printf("vetor[%i] = %i\n", i, vetor[i]);
    }

    return 0;

}

Browser other questions tagged

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