This is a homework assignment where I have to read a file into a dynamically allocated 2d array. The file format is
10
Jim 3.6
Jake 4.0
Will 3.0
Sara 3.4
Mike 2.5
Ellen 2.9
Melissa 3.9
Eric 3.8
John 3.5
Beth 3.9
where 10 is the number of students followed by the students and the gpa's. There is more to the program but I have not implemented it yet because I am getting a segmentation fault. The output I am getting when I print the array is
Jim 3.6
Jake 4.0
Will 3.0
Sara 3.4
Segmentation fault
I can see where the problem lies. If I raise value for row when I am allocating the rows of the array, all of the names print. I just do not see why I need to. From my understanding the row * sizeof(char*) should give me enough room for 10 entries. Its probably something I am going to smack myself in the head for but any help is appreciated. Thanks in advance.
Code:
#include <stdio.h>
#include <stdlib.h>
void sort();
int main()
{
sort();
return 0;
}
void sort()
{
FILE *fp;
fp = fopen("data.txt","r");
int col = 26;
int row;
fscanf(fp, "%d",&row); /*get # of students*/
char** buffer = (char **)malloc(row * sizeof(char*));
int i;
for(i=0; i < row; i++)
{
buffer[i] = (char *)malloc(col * sizeof(char));
}
/*char buffer[row][col];*/
for(i=0; i<row; i++)
{
fgets(buffer[i], sizeof buffer[i], fp);
}
for ( i = 1 ; i < row ; i++ ) /*print array*/
{
printf ( "%s", buffer[i] );
}
for(i = 0; i < col; i++){ /*free array*/
free(buffer[i]);
}
free(buffer);
}