#include "stdafx.h" #include <iostream> #define _CRT_SECURE_NO_WARNINGS using namespace std; char* sort_words(char* str) { char** strlist; int delimcnt = 0; int i; for (i = 0; str[i] != '\0'; i++) //считаем пробелы if (str[i] == ' ') delimcnt++; if(delimcnt == 0) { cout << "wrong input string"; return '\0'; } strlist = new char*[delimcnt]; //заполняем массив строк for (i = 0; i < delimcnt; i++) strlist[i] = new char[20]; for (int i = 0, j = 0, k = 0; str[i] != '\0'; i++) { if (str[i] == ' ') { if (j == 0) { strncpy(strlist[k], &str[j], i - j); strlist[k][i - j] = '\0'; k++; j = i; } else { j++; strncpy(strlist[k], &str[j], i - j); strlist[k][i - j] = '\0'; k++; j = i; } } } for (i = 0; i < delimcnt - 1; i++) //сортируем массив строк for (int j = i + 1; j < delimcnt; j++) if (strcmp(strlist[i], strlist[j])>0) { char* tmp = strlist[i]; strlist[i] = strlist[j]; strlist[j] = tmp; } for (i = 0; i < delimcnt; i++) cout << strlist[i]<<" "; //выводим массив строк } int main() { char* stroka; stroka = "here will be a memory leak "; // в конце добавляем пробел, чтоб отделить последнее слово sort_words(stroka); system("pause"); return 0; } 
  • Inside sort_words , of course, where else? - VladD
  • Why not use std::string and std::vector to reduce headaches? - αλεχολυτ
  • Did for myself, for educational purposes) - badmoonrising

2 answers 2

Where strlist guaranteed to stop being used, but as early as possible (closer to the place where memory was allocated).

    After the output, add:

     for (i = 0; i < delimcnt; i++) delete[] strlist[i]; delete[] strlist; код