Let's now make an array of pointers to your lines.
char * arr[3] = { s1, s2, s3 };
Now we need to call to sort qsort into which to transfer
1. arr array
2. number of elements in it 3
3. size of the element sizeof(char*)
4. and the comparison function to which the addresses of the elements are transmitted.
int cmp(const void * p1, const void * p2) { char * s1 = *(char**)p1; // p1 - указатель на указатель на char char * s2 = *(char**)p2; // p2 - указатель на указатель на char int len1 = strlen(s1); int len2 = strlen(s2); // Сравниваем длины if (len1 > len2) return 1; if (len1 < len2) return -1; return 0; }
It turns out something like
#include <stdio.h> #include <string.h> #include <stdlib.h> #define N 10 int cmp(const void * p1, const void * p2) { char * s1 = *(char**)p1; char * s2 = *(char**)p2; int len1 = strlen(s1); int len2 = strlen(s2); if (len1 > len2) return 1; if (len1 < len2) return -1; return 0; } int main(){ char s1[N] = "First", s2[N] = "Second", s3[N] = "One"; char * arr[3] = { s1, s2, s3 }; qsort(arr,3,sizeof(char*),cmp); for(int i = 0; i < 3; ++i) printf("%s\n",arr[i]); return 0; }
Well, to add length to each line - provided that the buffer allows you to place additional characters there! - you can use, for example, sprintf ( snprintf1 или sprintf_s` is safer, of course, but you yourself ...):
void addLen(char* s) { int len = strlen(s); // Пишем, начиная с len-того символа (добавляем к строке) sprintf(s+len," - %d",len); }
Those. end of main can be written, for example, as
for(int i = 0; i < 3; ++i) { addLen(arr[i]); printf("%s\n",arr[i]); }
just not forgetting to increase the N - 10 characters is not enough ...
Then you can do anything with an ordered array of pointers to strings - collect in one line, display, rewrite - in a word, of your choice :)
If I, of course, truly understood the task.
And yet - you can even immediately create an array of strings of type char s[N][M]; and sort it, rather than an array of pointers — by changing the parameters passed to qsort and the comparator, respectively.