I am still fairly new to C, under 3 months experience.
This is part of an assignment, just looking for some hints because I am not sure whats going wrong.
I have a file that I am sending to my readFile function. This function will transfer all the contents of the file into an int array.
The file contains values like this.
2 4
1 2 3 4
5 6 7 8
3 3
9 8 7
6 5 4
3 2 1
2 4
5 5 5 5
6 6 6 6
where 2 is the row count, and 4 is the columns, followed by the matrix of size 2x4
after transferred to the array, it looks like this:
data[2 4 1 2 3 4 5 6 7 8 3 3 9 8 7 6 5 4 3 2 1 2 4 5 5 5 5 6 6 6 6]
I am using ctr as my pointer, i pull off my row and col values, then travers the array row*col times and populate my Matrix field. It runs the first pass fine, but seg faults the 3rd time around.
The count variable is just from my matrixTester which just holds the total number of matrices in the file.
my readFile function, i bolded the loop that i think is causing the seg fault
Code:
void readFile(FILE *fin, Matrix **m){
int data[MAX*MAX];
//reads entire file into int array
int i = 0;
while(!feof(fin)){
fscanf(fin, "%i", &data[i]);
i++;
}
//ctr points to current position of data array
int ctr = 0;
for(i = 0; i<count; i++){
//assign row
m[i]->row = data[ctr];
//increment pointer
ctr++;
//assign col
m[i]->col = data[ctr];
//increment pointer
ctr++;
//DEBUG INFO
printf("m[%i].row: %i m[%i].col: %i\n", i, m[i]->row, i, m[i]->col);
printf("counter position: %i\n", ctr);
//DEBUG END
//gets size of array needed
int size = m[i]->row * m[i]->col;
//create memory for int array[size]
m[i]->loc = (int *)malloc(size * sizeof(int));
//DEBUG INFO
printf("created array size: %i\n", (m[i]->row * m[i]->col));
printf("data[%i]: %i \n", ctr, data[13]);
//DEBUG END
int j = 0;
for(j = 0; j < size; j++){
m[i]->loc[j] = data[ctr];
//DEBUG
printf("%i ", m[i]->loc[j]);
//DEBUG END
//increment pointer
ctr++;
}
//DEBUG INFO
printf("\n");
//DEBUG END
}
}
Here is my output
Code:
input.txt found.
m[0].row: 2 m[0].col: 4
counter position: 2
created array size: 8
data[2]: 1
1 2 3 4 5 6 7 8
m[1].row: 3 m[1].col: 3
counter position: 12
created array size: 9
data[12]: 9
9 8 7 6 5 4 3 2 1
Segmentation fault
I appreciate any help before hand.
Thanks