I'm working on Chapter 8 Challenge 3 from C Programming for the Absolute Beginner 2nd Edition. The program is supposed to sort an array of names alphabetically.
My program doesn't work. The main function without sort()
works, but the sort function is messed up; also strcmp()
seems to be used incorrectly, based on warning messages.
The compiler I'm using is gcc and I wrote the code with nano.
/* Uses strcmp() in a different function
to sort a list of names in alphabetical order */
#include <stdio.h>
#include <string.h>
void sort(char*, int);
void main() {
char strStates[4][11] = { "Florida", "Oregon", "California", "Georgia" };
sort(*strStates, 4); // 4 is the number of string in the array
printf("\nFour States Listed in Alphabetical Order\n");
int x;
for(x = 0; x < 4; x++)
printf("\n%s", strStates[x]);
}
void sort(char* strNames, int iStrings) {
char strPlaceholder[11] = { 0 };
int x;
int y;
for(x = 0; x < iStrings; x++) {
for(y = 0; y < iStrings - 1; y++) {
if(strcmp(strNames[y], strNames[y + 1]) > 0) {
strcpy(strPlaceholder, strNames[y + 1]);
strcpy(strNames[y + 1], strNames[y]);
strcpy(strNames[y], strPlaceholder);
}
}
}
}