0

I am new to C++, so I am trying to understand why the following code does not work:

std::sort(arr, arr + j);
for (int i = 0; i < j; i++) {
    cout << arr[i] << "\n";
}

Input I test: a, u, m

Output I expect: a, m, u

But getting still a, u, m.

Code in Studio

I am assuming it is because I put a pointer to the array into the sort() (that part of the code is in the function)? But I've read so many questions here on how to sort the pointers of the array and really got stuck. Could please somebody explain, in an easy way for a beginner to understand, why my code does not work, and how to fix it?

UPDATE:

struct Phones {
    char surname[50];
    int yearWhenPhoneRegistred;
    int phoneNumber;
};
Phones group[20];

void findDataByYear(struct Phones group[], int year, char *arr[]);

int main {
    int year = 0;
    char* surnameArr[20] = {};
    cout <<"Please, type the year value to apply the sorting: \n";
    cin >> year;
    findDataByYear(group, year, surnameArr);
    return 0;
}

void findDataByYear(struct Phones group[], int year, char *arr[]) {
    int j = 0;
    for (int i = 0; i < 20; i++) {
        if (group[i].yearWhenPhoneRegistred > year) {
            arr[j] = group[i].surname;
            j++;
        }
    }

    std::sort(arr, arr + j);
    printf("      Surname      |\n-------------------\n");
    for (int i = 0; i < j; i++) {
        cout << arr[i] << "\n";
    }
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Terry
  • 1
  • 1
  • Show a [mcve] please. Paste the code as text, no links, no images. – Thomas Matthews Aug 29 '21 at 17:46
  • Please share a [MCVE]. It works [when I try it](https://godbolt.org/z/dxo7s3dW1). – François Andrieux Aug 29 '21 at 17:47
  • @ThomasMatthews, added! – Terry Aug 29 '21 at 17:50
  • @FrançoisAndrieux added! – Terry Aug 29 '21 at 17:50
  • FYI, you don't need to use `struct` when declaring parameters, variables, members or return types. – Thomas Matthews Aug 29 '21 at 17:56
  • In C++, prefer to use `std::vector` or `std::array`. They are safer and are easier to pass to functions. See also `std::string` instead of character arrays. Arrays can overflow and underflow; `std::string` manages the memory for you. – Thomas Matthews Aug 29 '21 at 17:57
  • I was about to post an answer showing that it did correctly sort the CHARACTERS in the array you passed it, but I can see from the edit that you thought you were sorting multiple strings. You're passing it the wrong data type. Definitely prefer std::string and std::vector where appropriate. (yeah I'll follow up, just my previous answer would not have been helpful because it came before the edits/clarifications) – Kenny Ostrom Aug 29 '21 at 17:58
  • Thank you, but I am still curious, why the sorting for me does not work? – Terry Aug 29 '21 at 17:58
  • @KennyOstrom, could you please explain more? – Terry Aug 29 '21 at 17:59
  • Your arrays are never initialized; neither hard coded or via User input. – Thomas Matthews Aug 29 '21 at 17:59
  • BTW, the expression `arr[j] = group[i].surname;` copies pointers, not content. For C-Style strings (character arrays), you're going to need to use the `str*()` family of functions, such as `strcpy`, `strdup`, `strchr`. Also remember that when allocating and copying, you need to copy the terminating nul character. The `std::string` is so much simpler and easier. – Thomas Matthews Aug 29 '21 at 18:03
  • Also, consider using `cout` instead of `printf`. The `cout` works with `std::string` type directly; there is no `printf` format specifier for the `std::string` type. – Thomas Matthews Aug 29 '21 at 18:04
  • The `std::sort` function requires that your objects have some kind of ordering function; such as overloading `operator<`. You really don't want to use whatever default ordering function that `std::sort` is using for you structure. – Thomas Matthews Aug 29 '21 at 18:06
  • Finally, use a debugger. A debugger will allow you to single step through programs, watching values in variables. Your code is an excellent example to use for learning the debugger. – Thomas Matthews Aug 29 '21 at 18:08
  • There are a lot of errors not related to sort. But for the use of std::sort with a C-style array, https://stackoverflow.com/questions/5897319/how-to-use-stdsort-to-sort-an-array-in-c or work with std::vector Of course, you must define operator< on Phones. Also you can put some initial data directly into the question rather than doing keyboard input. I like to hardcode the test data to create a reliable reproduction. – Kenny Ostrom Aug 29 '21 at 18:08

1 Answers1

3

The basic problem is that, contrary to the title of your question, you're not trying to sort a char[] array (an array of characters), you're trying to sort a char*[] array (an array of pointers). So, the default sorter (what you get if you use std::sort() without a third functor argument) will just compare the pointers themselves and sort them in memory order, without regard to the characters they are pointing at.

If you want to sort in lexical order, you need to compare the strings:

std::sort(arr, arr+j, [](char *a, char *b)->bool { return strcmp(a, b) < 0; });
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Chris Dodd
  • 119,907
  • 13
  • 134
  • 226