'Given names in a matrix form, print them in ordered form in a single column array

So i finally arrived at memory allocation and pointers so im quite new at this so i apologize in advance if i made some rookie mistakes.

The exercise as i stated in case i wasnt clear says: Given the names in a matrix form print the result in a single column array in ordered alphabetical form.

We read the data from a file and we have to print them into another.

I've only been able to dynamically allocate the memories but i am stuck as to how to order it. At first i thought since it was in a matrix from i could probably just print it in a file in column form and then order it alphabetically but that would mean i had to allocate more memory to other stuff and i thought that this was deffinitely the long way around and difinitely not the optimal way.

This is the file data:

4 3 
milano torino venezia 
bari genova taranto 
firenze napoli roma 
bologna cagliari palermo

and the result should look like this

12
bari 
bologna 
cagliari
firenze
genova
milano
napoli
palermo
roma
taranto
torino
venezia

and this is the code so far:

int main() {
  FILE * file;
  FILE * file2;
  file = fopen("file", "r");
  file2 = fopen("file2", "r"); // here i am using "r" so it doesnt keep annoying me every time 
  // i compile the program
  if (file == NULL || file2 == NULL) {
    printf("Error in opening the files!!!");
    exit(1);
  }
  int n, m;
  int i = 0, j = 0;
  fscanf(file, "%d %d", & n, & m);
  char name[N + 1];
  char ** * v;
  v = (char ** * ) malloc(n * sizeof(char ** ));
  if (v == NULL) {
    printf("Memory allocation error.\n");
    exit(EXIT_FAILURE);

  }
  for (i = 0; i < n; i++) {
    v[i] = (char ** ) malloc(m * sizeof(char * ));
    if (v[i] == NULL) {
      printf("Memory allocation error.\n");
      exit(EXIT_FAILURE);

    }
  }
  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++) {
      fscanf(file, "%s", name);
      v[i][j] = strdup(name);
      if (v[i][j] == NULL) {
        printf("Memory allocation error.\n");
        exit(EXIT_FAILURE);

      }
    }
  }

  return 0;
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source