I am sorting my array of car two ways. one by year which is shown below. and another one by make. Make is a char* How do I compare strings when I just have pointers to the
In C its strcmp() function as already stated. In C++ you can use the compare() function.
C:
char str1[10] = "one";
char str2[10] = "two";
if (strcmp(s, t) != 0) // if they are equal compare return 0
C++
string str1 ("one");
string str2 ("two");
if (str1.compare(str2) != 0) // if they are equal compare return 0
Make sure the char * isn't null, and if you want, look for the stricmp() function for case insensitive comparisons. Otherwise, use strcmp().
char * actually represents the memory address of the first character in each string. So you don't really want to be comparing the values of the pointers, but the contents they point to.
I think you need to use the strcmp() function.
When you need to compare two char pointers specifically, you can compare them in the usual way: by using comparison operators <
, >
, ==
etc.
The issue in ths case is that you don't need to compare two char pointers. What you do need though, is to compare two C-style strings these char pointers are pointing to. In order to compare the C-style strings, you have to use the standard strcmp
function.
On top of that, the approach to handling null elements in your sorting algorithm doesn't seem to make any sense whatsoever. Imagine an input array that contains alternating null pointers and non-null pointers. It is obvious, that your sorting algorithm will never sort anything, since the condition in your if
will never be true. You need to reconsider your handling of null elements. Of course, first of all, you have to decide what to do with them. Ignore and leave in place? Push to one end of the array? Somethng else?
You should really use qsort
(in C, #include <stdlib.h>
) or std::sort
(in C++, #include <algorithm>
) instead of a bubble sort like this. If it's C++ and you take @T.E.D.'s advice to use std::string
instead of raw C strings, you don't even have to specify a comparison because the <
operator will be used and will do the right thing.
strcmp() will help you to compare two char* http://www.cplusplus.com/reference/cstring/strcmp/?kw=strcmp