0

why is my code not sorting the names alphabetically?

#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char temp[100] ; char S1[] = "Adam" ; char S2[] = "Yusha" ; char S3[] = "John" ; char S4[] = "Steve" ; char *s[]= { S1, S2, S3, S4 } ; for (int j=0 ; j<4 ;j++) { for (int i=0;i<3;i++) { if (strcmp(s[i], s[i+1])==1) { strcpy(temp,s[i]) ; strcpy(s[i], s[i+1]) ; strcpy(s[i+1], temp) ; } } } for (int i=0;i<4;i++) { printf("%s ",s[i]) ; } return 0 ; } I am trying to sort a sequence of names alphabetically. I know how to do it using a 2D character array but it isnt working on an array of char pointers. I first tried storing the names directly in the initialization of char*s[ ], but i realized that using that method, strcpy wont work since "Adams" for eg is a string literal and cannot be modified. Hence, i decided to copy the names into different character arrays. The technique i am using for sorting is called Bubble Sorting. Although this same technique works for an array of ints or floats, it just isnt, for some reason, working on character arrays. If i use a nested loop, i am losing names. That is, after the sorting when i print all the names, i am only left with 2 names, the remaining 2 are lost!! Could anyone please tell what is wrong with my code. Your help is highly appreciated. Thanks!!

15th Dec 2018, 5:54 AM
Yusha Arif
Yusha Arif - avatar
3 Respuestas
+ 1
The answer is quite complicated if you are a beginner, I will try to make it simple but do not hesitate to ask me questions if you did not understood. In memory, your arrays (S1, S2, ..) are stored one next to the other. As you did not specified their size but put a value, their size is the length of the value + 1. Sometimes, you try to store more than you can in the array (in fact only one character more than what it can handle) so the terminating character "\0" is written in the previous array (S1 for S2, S3 for S2, ...). When you, then, copy something in the previous array, you erase the "\0" When showing the string with the "\0" erased, the previous one will be printed as if they were concatenated. Idea of correction : put a size to all your arrays which is at least the size of the longest string + 1
15th Dec 2018, 4:05 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar