Search code examples
cstrcmpstrcpy

Sorting a pre-defined list of names


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);
            }
        }
    }
}

Solution

  • Not meant as an answer but as a hint to let you get forward. A two dimensional array like char[4][11] is something different than a pointer to a (sequences of) characters like char*.

    Suppose the following code:

    char *s = "Florida"; // lets pointer 's' point to a sequence of characters, i.e. { 'F', 'l', 'o', 'r', 'i', 'd', 'a', '\0' }
    char arr[2][11] = { "Florida", "New York" };
    

    Then an expression like s[1] is equivalent to *(s + sizeof(char)), which is *(s+1), whereas an expression like arr[1] is equivalent to *(arr + sizeof(char[11])), which is *(arr + 11), not *(arr + 1). The "sizeof"-part is done by the compiler and is derived from the type of the variable. Hence an argument of type char* behaves different than an argument of type char[11].

    The following code might help you forward:

    void print (char array[][11], int n) {
    
        for(int i=0;i<n;i++)
            printf("%d:%s\n",i,array[i]);
    }
    
    int main() {
    
        char strStates[4][11] = { "aer", "adf", "awer", "aert" };
        print (strStates,4);
    
        return 0;
    }