I am pretty new to programming and I am getting a segmentation fault and I have no idea where this is happening.
Code:
#include <stdio.h>
#include <stdlib.h>
#define FIELDWIDTH 3 //The width of the hopscotch field.
FILE *in; //Pointer to files
FILE *out;
int max_score(int *tally_row, int middle_index);
int** alloc_no_of_marbles(int field_length, int fieldWidth);
int** alloc_score_of_each_square(int field_length, int fieldWidth);
int main(void)
{
char inFileName[] = "hopscotch.dat"; //Open files for reading
char outFileName[] = "hopscotch.out";
int field_length, i, j;
fscanf(in, "%d", &field_length);
int **no_of_marbles = alloc_no_of_marbles(field_length, FIELDWIDTH);
int **score_of_each_square = alloc_score_of_each_square(field_length, FIELDWIDTH);
for(i=0; i<field_length; i++)
{
for(j=0; j<FIELDWIDTH; j++)
{
fscanf(in, "%d", &no_of_marbles[i][j]);
}
}
for(i=0; i<field_length; i++)
{
for(j=0; j<FIELDWIDTH; j++)
{
score_of_each_square[i][j] =
( ((i-1) < 0) ? 0 : score_of_each_square[i-1][max_score(score_of_each_square[i-1],j)] )
+ no_of_marbles[i][j];
}
}
int path_score = score_of_each_square[field_length-1][max_score(score_of_each_square[field_length-1],1)];
char hop_path[field_length+1];
int current_row = field_length, current_pos = 1, previous_pos;
for(i=current_row; i>=0; i--)
{
if(i==0) previous_pos = 1;
else previous_pos = max_score(score_of_each_square[i-1], current_pos);
switch(current_pos - previous_pos){
case -1: hop_path[i] = 'L';
break;
case 0: hop_path[i] = 'D';
break;
case 1: hop_path[i] = 'R';
break;
}
current_pos = previous_pos;
}
fprintf(out, "Maximum possible score: %d\n", path_score);
fprintf(out, "A path that achieves this score: ");
for(i=0; i<=field_length; i++)
fprintf(out, "%c", hop_path[i]);
fprintf(out, "\n");
return 0;
}
int max_score(int* tally_row, int middle_index){
int k, value = 0, max_value_index = -1;
for(k=middle_index-1; k<=middle_index+1; k++)
{
if(k >= 0 && k < FIELDWIDTH)
if(tally_row[k] > value)
{
value = tally_row[k];
max_value_index = k;
}
}
return max_value_index;
}
int **alloc_no_of_marbles(int field_length, int fieldWidth)
{
int **hopArr;
int *aux1;
int i, j;
aux1 = (int *) malloc(field_length*fieldWidth*sizeof(int));
if (aux1 == NULL) exit(1);
hopArr = (int **) malloc(field_length*sizeof(int *));
if(hopArr == NULL) exit(1);
for(i=j=0; i<field_length; i++, j+=fieldWidth)
hopArr[i] = &aux1[j];
return hopArr;
}
int **alloc_score_of_each_square(int field_length, int fieldWidth)
{
int **talArr;
int *aux2;
int i, j;
aux2 = (int *) malloc(field_length*fieldWidth*sizeof(int));
if (aux2 == NULL) exit(1);
talArr = (int **) malloc(field_length*sizeof(int *));
if(talArr == NULL) exit(1);
for(i=j=0; i<field_length; i++, j+=fieldWidth)
talArr[i] = &aux2[j];
return talArr;
}