Segmentation fault C in Dev C ++

0

I wanted to know if someone could help me with this error in my code. I do not understand why it does not continue after the accountant takes the value of 10.

This is my code:

#include<stdio.h>
#include<windows.h>
int main() {
    int Nalumnos, cont;
    Nalumnos=0;cont=0;
    int x[Nalumnos];
    scanf("%d",&Nalumnos);

    do{
    cont=cont+1;
    x[cont]=cont;
    printf("Alumno numero %d\n",x[cont]);

    }while(cont<Nalumnos);

return 0;
}
    
asked by Roner Ortega Cueto 18.04.2016 в 00:59
source

2 answers

5
int Nalumnos;
Nalumnos=0;
int x[Nalumnos];

Have you ever seen a vector of size 0 in mathematics? Declare a vector, in your case x , with size 0 will never be a good idea.

You should try to exchange the declaration of x and the next line, which is where you initialize Nalumnos :

scanf("%d",&Nalumnos);
int x[Nalumnos];

And, please, for future queries, try not to put the code inside an image, as this makes it impossible to copy your code and you have to rewrite it. With this type of practice you get people to lose interest in answering you.

Greetings.

    
answered by 18.04.2016 в 09:04
1

Your error is how much you try to declare int x[Nalumnos]; since at that point Nalumnos is zero. You can ponder the statement after the scanf which is when you know the size of the array but if you want to declare the variable before you can set aside memory and then release it.

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

int main() {
    int Nalumnos, cont;
    Nalumnos=0;cont=0;
    int *x;
    scanf("%d",&Nalumnos);
    x = (int*) malloc (sizeof(int)*Nalumnos);

    do{
        cont=cont+1;
        x[cont]=cont;
        printf("Alumno numero %d\n",x[cont]);

    }while(cont<Nalumnos);

    free(x);
    return 0;
}
    
answered by 05.05.2016 в 18:07