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 them?
int i, j;
for(i=0; i<100; i++){
for(j=0; j<100-i; j++){
if(carArray[i]!=NULL && carArray[j]!= NULL && carArray[j+1]!=NULL){
if(carArray[i]->year > carArray[j+1]->year){
swap(carArray[j], carArray[j+1]);
}
}
}
}
The above method works for int’s (year). How can I make it work for char pointers?
In pretty much either one, the way is to call
strcmp. If your strings (for some weird reason) aren’t NUL terminated, you should usestrncmpinstead.However, in C++ you really shouldn’t be manipulating strings in char arrays if you can reasonably avoid it. Use
std::stringinstead.