2D array of chars prints differntly each time

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
int main (void)
{
//Local Declarations
int size;
int students_friends[MAX_STUDENTS][MAX_STUDENTS] = { {0 } };
int number_friends[MAX_STUDENTS];
char names[MAX_STUDENTS][NUM_NAMES] = { {0} };


//Statements
size = get_data(students_friends, names, size);
frequency_friends(students_friends, number_friends, size);
//list_friends(students_friends, names,number_friends, size);

for (int row = 0; row < size; row++)
   for (int col = 0; col < size; col++)
        printf("%c", names[row][col]);


}

int get_data (int students_friends[][MAX_STUDENTS],char names[][NUM_NAMES],
int size)
{
//Local Declarations
int data_in;
char name_data;
int loader;
FILE* fp_data;
char whitespace;
whitespace = NULL;

//Statements
loader = 0;

//Checks that file opens
if ((fp_data = fopen ("clubs.txt", "r")) == NULL)
   {
      printf("Error opening file\a\a\n") ,
     exit (100);
   }
//Reads first integer in text file and assigns it to size
if (fscanf(fp_data, "%d", &data_in) != EOF && loader == 0)
    {
     size = data_in;
     printf("%d", size);
     loader++;
    }
//Reads the names in text file into 2D array
 for (int row = 0; row < size; row++)
    for (int col = 0; col < size; col++)
        if (loader > 0 && loader <= (size * size) &&
           fscanf(fp_data, "%c", &name_data) != EOF
           && name_data != whitespace)
         {
             names[row][col] = name_data;
             printf("%c", names[row][col]);
             loader++;
         }
printf("\n");
//Reads the remaining numbers in text file into 2D array
for (int row = 0; row < size; row++)
      for (int col = 0; col < size; col++)
           if (loader > (size * size) && loader <= (size * size) + (size * size) &&
              fscanf(fp_data, "%d", &data_in) != EOF)
             {
               students_friends[row][col] = data_in;
              printf("%d ", students_friends[row][col]);
              //After four numbers, prints a new line
               if (!(loader % size))
               printf("\n");
              loader++;
             }
return size;
}

The bold part indicates where during the for loop the 2D array "names" prints correctly. However, when I try to print "names" anywhere else. It comes out wrong. Any help guys? I believe it is just a logic error that I can't find, but perhaps its something else?

During the for loop it prints
Ami
Ann
Ben
Dan

In any other part of the program it prints
Am

An

Be

Dan



Why are you using characters btw? Is it not possible to rather use strings and store them in an array or a vector?
Last edited on
What does frequency_friends(students_friends, number_friends, size) do? Does it modify size at all?
Last edited on
Topic archived. No new replies allowed.