Here is my code:
int main(int argc, char **argv) {
int numberOfStrings, remaining;
printf("Input number of strings:");
scanf("%d", &numberOfStrings);
// equalizing remaining check count for bubble sort algorithm
remaining = numberOfStrings - 1; // strCount - 1 is adequate for bubble sort element count
char strings[numberOfStrings][50], temp[50];
int count = 0, cmp;
printf("Input string %d:", numberOfStrings);
for (int i = 0; i < numberOfStrings; i++)
scanf("%s", strings);
while (remaining != 0) {
// bubble sort
cmp = strncmp(strings[count], strings[count+1], sizeof(strings[count]-1));
if (cmp > 0) {
strncpy(temp, strings[count], sizeof(temp)-1);
strncpy(strings[count], strings[count+1], sizeof(strings[count]-1));
strncpy(strings[count+1], temp, sizeof(temp)-1);
}
count++;
--remaining;
}
printf("\n--------------------------------------------\n\n");
for(int i = 0; i < numberOfStrings; i++)
printf("%s\n", strings[i]);
return 0;
}
xx
console:
Input number of strings:3
Input string 3:ddddddddddd
vvvvvvvvvvv
bbbbbbbbbb
--------------------------------------------
bbbbbbbbbb
□□
You read all strings (you really mean words) at the same position: instead of
scanf("%s", strings), you should write:Also note that your bubble sort is incorrect: when you swap 2 words, you should backtrack to compare with the previous one. Furthermore, there is no need for
strncmpnorstrncpy.Here is a modified version: