Search code examples
pointersfstreamstrtokfile-read

Printing char pointer in C - I keep getting bad formatting


I am reading a line from a file containing the names of people, first line contains names of males, and seconds line contains names of females. Then I want to store these names in two arrays, one for males, one for females, however when I print them I get weird things. I'm not sure if I am not reading them correctly, or printing them incorrectly

    char line[100];      //holds line read
    char *item;         //item in a line
    char *item2;
    int participants = 5;   //number of people in the event

            char* maleNames[participants];
            char* femaleNames[participants];

            fgets(line, 255, file);
            int i;
            item = strtok(line, " ");
            for(i=0; i<participants; i++)
            {
                maleNames[i] = item;  
                item = strtok(NULL, " ");


               }

        //read female names now
        fgets(line, 1024, file);
        item2 = strtok(line, " ");
        for(i=0; i<participants; i++)
        {
            femaleNames[i] = item2;
            item2 = strtok(NULL, " ");
        }

These lines are read

John Jeffrey Adam Mark Peter
Jenny Alice Sally Wendy Amanda

However when I print them out like this:

        for(i=0;i<participants;i++)
        {
            printf("%s %s\n", maleNames[i], femaleNames[i]);
        }

I get something so different:

Jenny Jenny
 Alice
ally Sally
Wendy Wendy
 Amanda

Note: if I print the names of males right after they're read before reading the female names, then they are printed correctly


Solution

  • Not paying attention to other problems (like the size, 255 and 1024, you pass to fgets when your buffer is only 100 characters long), this problem most likely comes from the fact that you are using the same buffer, char line[100], for both calls to fgets(). Strtok returns a pointer to a character in the line buffer, so when you store in "line" the female names, all these pointers, relative to line when line contained the male names, are now invalid. Try storing the female line in other buffer, it should work.

    EDIT: Sorry if the "not paying attention..." sounds discouraing. Nothing more far away from my intention. Everyone make mistakes everytime, specially when learning. I wish you good luck with the process :)