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

// Сравнение слов - через указатели на указатели
int wordsCmp(const void* a, const void* b)
{
    const char * c = *(const char **)a;
    const char * d = *(const char **)b;
    return strcmp(c,d);
}

char * sortIt(const char * str)
{
    // Находим все слова - указатели на них. Их никак не больше половины длины строки.
    const char ** words = malloc(sizeof(char*)*strlen(str)/2);
    const char * c = str;
   
    int idx = 0;
    while(*c == ' ') ++c;
    words[idx++] = c++;
    for(;*c;++c)
        if (*c != ' ' && *(c-1) == ' ') words[idx++] = c;

    // Сортировка массива указателей
    qsort((void*)words,idx,sizeof(char*),wordsCmp);

    // Копия строки (чтоб нужной длины была
    char * s = malloc(strlen(str)+1);
    char *z = s;
    *s = 0;
    // Запись слов в новую строку
    for(int i = 0; i < idx; ++i)
    {
        for(const char * t = words[i]; *t && *t != ' ';)
            *z++ = *t++;
        if (i < idx-1) *z++ = ' ';
    }
    *z = 0;


    free(words);
    return s;
}

int main()
{
    char str[] = "Sorry I can not write this simple program";
    printf("%s\n", str);
    char * res = sortIt(str);
    printf("%s\n", res);
    free(res);
}
