An alphanumeric sorting algorithm with scanf c

Viewed 549

I have created a program that sorts strings in an array in alphanumeric order.

But my question is how to make it so that when you run the program, it asks for the strings (with a scanf but the question is how with a char const *array?) and then the program sorts and creates a new file in which the result will be saved.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

FILE *myFile = NULL;
static void consoleWrite(char const **a, size_t b) {
    size_t i;
    for (i = 0; i < b; i++)
        fprintf(myFile, "%s ", a[i]);
    printf("\n");
}

static int string_cmp(void const *i, void const *j) {
    char const *const *pointerI = i;
    char const *const *pointerJ = j;   
    return strcmp(*pointerJ, *pointerI); // comparaison de la chaine de caractère !
}

int main(void) {
    char const *array[] = { 
        "01", "fdf", "gffg", "FRSTM-PFOV1DK", "FRSTM-KEFF2OQHT"
    };

    myFile = fopen("file.ini", "a+");
    long array_size = sizeof array / sizeof *array;

    qsort(array, array_size, sizeof *array, string_cmp);
    consoleWrite(array, array_size);
    printf("Le tri a été effectué ! ");

    return 0;
}

I would like to save my data in the variable array and then with this variable I sort.

1 Answers

You can allocate memory dynamically for this. Asking for first the number of strings the user will enter, then allocating a char* array of that size. Then reading in the strings, saving it a buffer, allocating enough memory for the entered string and copy the buffer content to it. Like so

int main(void) {
  int array_size = 0;
  char **array;
  char buffer[256];

  myFile = fopen("file.ini", "a+");

  scanf("%d", &array_size);
  array = malloc(array_size * sizeof(char*));

  for(int i = 0; i < array_size; i++) {
    scanf("%s", buffer);
    array[i] = malloc(strlen(buffer) + 1);
    strncpy(array[i], buffer, strlen(buffer) + 1);
  }

  qsort(array, array_size, sizeof *array, string_cmp);
  consoleWrite(array, array_size);
  printf("Le tri a été effectué ! ");

  for(int i = 0; i < array_size; i++)
    free(array[i]);
  free(array);

  return 0;
}
Related