c - Segmentation fault when introducing a second for loop -


this program takes number file , introduces matrix n * n (n number taken) matrix 0.

the problem if 1 for 00, 11, 22, ... there isn't problem, problem appears when introduce second for. program returns me segment violation.

#include <stdio.h>  int main(int argc, char* argv[]) {   file* fitxer;   int n, m, i,j;   int inc[n][n];   fitxer=fopen(argv[1], "rt");          if(fitxer == null)   {    fprintf(stderr, "error: el fitxer %s no es pot obrir\n", argv[1]);     return 1;   }   else   {      if(!fscanf(fitxer, "%d %d", &n, &m));       printf("%d, %d\n", n, m);       for(i=0; i<n; i++)      {        for(j=0; j<n; j++)        {          inc[i][j]=0;          printf("%d  ", inc[i][j]);        }      }      printf("\n");     }    fclose(fitxer);          printf("bien!\n");   return 0; } 

here:

int inc[n][n]; 

n in uninitialized. leads undefined behavior. move after

if(!fscanf(fitxer, "%d %d", &n, &m)); 

to fix problem. if above makes no sense. fix using:

if(fscanf(fitxer, "%d %d", &n, &m) != 2) //if fscanf failed scan 2 integers file {     printf("error reading file");  //print error message     return 1;                           //exit program } 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -