I am trying to do the following coding challenge in C:
Challenge: Using the C language, have the function AlphabetSoup(str) take the str string parameter being passed and return the string with the letters in alphabetical order (ie. hello becomes ehllo). Assume numbers and punctuation symbols will not be included in the string.
Attempt:
#include <stdio.h>
#include <stdlib.h>
int cmpfunc(const void* val_1, const void* val_2){
return (*(char *)val_1 - *(char *)val_2);
}
int str_size(char* str[]){
int size = 0;
while(str[size] != '\0')
size++;
return size;
}
void AlphabetSoup(char * str[]) {
qsort(str,str_size(str), sizeof(char), cmpfunc);
printf("%s", str);
}
int main(void) {
// disable stdout buffering
setvbuf(stdout, NULL, _IONBF, 0);
// keep this function call here
AlphabetSoup(gets(stdin));
return 0;
}
I am not getting any output for this code. I think the problem is the cmpfunc function. I am not implementing it correctly. I neither understand how it works inside qsort. My understanding is that val_1 and val_2 are pointers to two chunks of memory in the array and somehow I have to cast these chunks to the right type.
I am also getting a non-zero status for the following code:
void AlphabetSoup(char * str[]) {
int str_size_ = str_size(str);
int int_rpr[str_size_];
int i;
for(i = 0; i < str_size; i++){
int_rpr[i] = (int)str[i];
}
printf("%i", str_size_);
//printf("%s", str);
//qsort(int_rpr,str_size_, sizeof(int), cmpfunc);
//for(i = 0; i < str_size; i++){
// printf("%c", str[i]);
// }
}
when I get rid of int_rpr[i] = (int)str[i];and replace it by any random statement like int b; b = 0; , it works.
coding challenge link: https://coderbyte.com/editor/Alphabet%20Soup:C