Hi, my assignment is to read in a file from a command line parameter and use malloc to allocate memory for the contents. I declared three double pointers in my main function to pass into the read_file() method and every time I run the program, it seg faults. Can someone please help me out with my use of pointers. I don't think I have it quite right in dereferencing the pointers.
Here is my code:
CODE
int main(int argc, char *argv[])
{
int **scores;
char **ids, **labels;
read_file(argv[1], &labels, &ids, &scores);
return 0;
}
void read_file(char *argv, char ***labels, char ***ids, int ***scores)
{
FILE *fp;
int numrows, numcols, i, j;
char line[256], *ptr;
fp = fopen(argv, "r");
fgets(line, 256, fp);
numrows = atoi(strtok(line, " "));
numcols = atoi(strtok(NULL, " "));
*labels = (char**)malloc(numcols * sizeof(char));
fgets(line, 256, fp);
ptr = strtok(line, " ,");
*labels = (char**)malloc(numcols * sizeof(char*));
for(i = 0; i < numcols; i++)
{
*labels[i] = (char*)malloc(strlen(ptr)+1);
strcpy(*labels[i], ptr);
ptr = strtok(NULL, " ,");
}
*ids = (char**)malloc(numrows * sizeof(int*));
*scores = (int**)malloc(numrows * sizeof(int*));
for(i = 0; i < numrows; i++)
{
fgets(line, 256, fp);
ptr = strtok(line, " ,");
*ids[i] = (char*)malloc(strlen(ptr)+1);
strcpy(*ids[i], ptr);
*scores[i] = (int*)malloc((numcols-1) * sizeof(int));
for(j = 0; j < numcols - 1; j++)
*scores[i][j] = atoi(strtok(NULL, " ,"));
}
}
Thanks a bunch,
Gautam