I'm learning C so I thought to apply it to miniproject on reddit. The smorse function takes in a string and spits out some morse code. It works if you supply the function with only lowercase letters. I feel awkward making a first for loop in my smorse function to calculate the size of buffer I need to malloc and then making a second for loop to add the characters.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char **master = NULL;
char* smorse(char *str) {
int i;
char *ele;
int end = strlen(str);
char *output = "";
int totalSize = 0;
for (i = 0; i < end; i++) {
ele = master[(*str) - 97];
totalSize += sizeof(ele) * sizeof(char);
str++;
}
output = malloc(totalSize);
str -= end;
for (i = 0; i < end; i++) {
ele = master[(*str) - 97];
strcat(output, ele);
str++;
}
return output;
}
int main(int argc, char *argv[]) {
int i;
char key[] = ".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..";
master = (char **)malloc(26 * sizeof(char *));
char *ele = strtok(key, " ");
for (i = 0; i < 26; i++) {
if (i != 0)
ele = strtok(NULL, " ");
master[i] = (char *)malloc(sizeof(ele) * sizeof(char));
master[i] = ele;
}
printf("%s\n", smorse("sos"));
printf("%s\n", smorse("daily"));
printf("%s\n", smorse("programmer"));
printf("%s\n", smorse("bits"));
printf("%s\n", smorse("three"));
free(master);
return 0;
}