I got your code working. Tough assignment for me. (still learning C). Been working on it since noon, about 9-10 hours of work I guess. Thought I'd share.
One of the issues you had was the fscanf() reading the count. It was leaving the CRLF in the input stream, and the first fgets() to read a record read only the CRLF.
Also, your pointers are a level deeper than the need to be.
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int read_file(char **first_name[], char **last_name[], char **age[]) {
int count, i;
char line[80];
FILE *fp = fopen("names.txt", "r");
if (fp==NULL) return 0 ;
//printf("fp = %08X, *fp = %08X\n", &fp, fp );
fgets(line, 80, fp); //count = how many names in the file on the first line
count = atoi(line) ;
*last_name = malloc(count * sizeof(char *));
//printf(" 3 word area for last name pointers starts @ %p\n", *last_name);
*first_name = malloc(count * sizeof(char *));
//printf(" 3 word area for first name pointers starts @ %p\n", *first_name);
*age = malloc(count * sizeof(char *));
//printf(" 3 word area for age pointers starts @ %p\n", *age);
for (i = 0; i < count; i++) {
fgets(line, 80, fp);
(*last_name)[i] = malloc( 21 * sizeof(last_name) ); // area for last name
(*first_name)[i] = malloc( 21 * sizeof(first_name) ); // area for first name
(*age)[i] = malloc( 4 * sizeof(age) ); // area for age
strcpy( (*last_name)[i] , strtok(line,", \n") ) ;
strcpy( (*first_name)[i], strtok(NULL,", \n") ) ;
strcpy( (*age)[i] , strtok(NULL,", \n") ) ;
}
return count ;
}
int main() {
int i, count ;
char **ages, **first_names, **last_names ;
char **ln, **fn, **age ;
count = read_file(&first_names, &last_names, &ages);
ln = (char **) last_names ;
fn = (char **) first_names ;
age = (char **) ages ;
for ( i = 0 ; i < count ; i++ ) {
printf("Lastname=%s, Firstname=%s, Age=%s\n",
*ln,
*fn ,
*age ) ;
ln += 1 ;
fn += 1 ;
age += 1 ;
}
return 0;
}
I added code at the end to print out the records too. It's really not that much code when it comes down to it.
Todd