user12341155
user12341155

Reputation: 1

I am encountering a segmentation fault in my c code

I am trying to update a 2d array generation by generation. In order to do this, I need to take two arguments: generation number and the initial input txt that contains a 2d array. But no matter what I wrote, there are always segmentation fault in my code.

I am trying to read a 2d array from the input file. The file should look similar to this: 1 1 1 0 0 0 0 0 0 0......

int main(int argc, char *argv[]) {
  // take arguments//
  char* generation;
  char* filename;
  if (argc < 2)
    {
        printf("Error\n");
        exit(1);
    }
  else{
    generation = argv[1];
    filename = argv[2];
  }
  // read file as a 5*5 matrix//
  FILE *file;
  file = fopen (filename,"r");
  //5*5 matrix//
  int gen = atoi(generation);
  int cell[5][5];
  int i=0;
  int j=0;
  for (i=0;i<5;i++){
    for (j=0;j<5;j++){
      fscanf (file, "%d",&cell[i][j]);
    }
  }
  fclose(file);

Thank you so much!!!

Upvotes: 0

Views: 51

Answers (1)

gioretikto
gioretikto

Reputation: 229

In your code you're not using the variable generation but I suppose it should be used to store the matrix dimension. If it is the case in total you're reading 3 arguments so argc should be 3.

If you are reading a file formatted like this:

1 2 3 4 5
6 7 8 9 10
1 1 3 4 5
6 7 8 9 0

The arguments passed at the console are: ./a.out dimension matrix. A simple but unsafe code (it doesn't check the dimension input by the user) is the following:

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

int main(int argc, char *argv[]) {

    FILE *fp;
    char *filename;
    char *generation;

    if (argc < 3)
    {
        printf("Error\n");
        exit(1);
    }

    else {
        generation = argv[1];
        filename = argv[2];
        fp = fopen(filename, "r");

        if (fp == NULL) {
            fprintf(stderr, "Error: Cannot open file %s for reading\n", filename);
            exit(1);
        }       
   }

   int dim = atoi(generation);   

   int i, j, cell[dim][dim];

   for (i = 0; i < dim; i++) {
       for (j = 0; j < dim; j++) {
           if (fscanf(fp, "%d ", &cell[i][j]) != 1) {
               fprintf(stderr, "invalid input for cell[%d][%d]\n", i, j);
               fclose(fp);
               exit(1);
           }
       }
   }   

   fclose(fp);

   /*Print the matrix */

   for (i = 0; i < dim ; i++)
   {
       for (j = 0; j < dim ; j++)
       {
           printf("%d ", cell[i][j]);
       }
       printf("\n");
   }

   printf("\n");

   return 0;
}

Upvotes: 1

Related Questions