I'm trying to translate a sentence into morse code. I have a morse.txt file with this type of content :
'-','-','-','-','-',0, /* Caractère 0 */
'.','-','-','-','-',0, /* Caractère 1 */
'.','.','-','-','-',0, /* Caractère 2 */
In order to translate each letter from the sentence I thought about create a 2 dimension array in which we would find a letter and its translation in morse. Here's my struct
typedef struct
{
char lettre;
char *morse;
} t_morse;
I created a function returning that array :
t_morse *loadTab()
{
t_morse *tabMorse = malloc(LETTER_NUMBER * sizeof(t_morse));
ssize_t read;
size_t len = 0;
char index = 0, k = 0, j;
char *line = NULL;
FILE *f = fopen("morse.txt", "r");
if (f == NULL)
{
fprintf(stderr, "Fichier : %s n'existe pas\n","morse.txt");
exit(0);
}
while (read = getline(&line, &len, f) != -1 && line != NULL)
{
char *morse = malloc(6 * sizeof(char));
char *stringfinal = malloc(50 * sizeof(char));
strcpy(stringfinal, line);
k = 0;
for (j = 0; j < strlen(stringfinal); j++)
if (stringfinal[j] == '-' || stringfinal[j] == '.')
morse[k++] = stringfinal[j];
tabMorse[index].morse = morse;
tabMorse[index].lettre = index + 48;
printf("lettre : %c, morse : %s\n", tabMorse[index].lettre, tabMorse[index].morse);
index++;
free(morse);
free(stringfinal);
}
fclose(f);
for (index = 0; index < LETTER_NUMBER; index++)
{
printf("toto %c : %s\n", tabMorse[index].lettre, tabMorse[index].morse);
}
return tabMorse;
}
But it doesn't as it would be : when executing the programm, the first printf (printf("lettre : %c, morse : %s\n", tabMorse[index].lettre, tabMorse[index].morse);) show me the thing that I want. However after this when I want to iterate through that array and display the structs, the letter field is the right but in the morse field I get a "" string, and I don't know why.
You can see below, a screen of the stdout when launching the program :
Do you know why it acts like that ?

