Hello yet again for some happy fun time! woohoo!
Today's topic: pointers to pointers
And here we go...
So, I'm slightly confused (who is it on the forums who's little quote is "eternally confuzzled"? Or something like that...well it's applying to me quite a bit at the moment haha). Anyways, I wrote this little program that creates an array of pointer to strings for the days of the week...then it sorts them alphabetically using strcmp(). Now, I got the program working and everything but that was simply a result of trial and error and no pure skill on my part. What got me was the bold line in the code (in the order() function):
Code:
#include <iostream>
#include <cstring>
using namespace std;
const int DAYS = 7;
void bsort(char**, const int);
void order(char**, char**);
int main()
{
char* arrweek[DAYS] = { "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday" };
cout << "Presorted list:\n";
for (int i = 0; i < DAYS; i++)
cout << arrweek[i] << endl;
bsort(arrweek, DAYS);
cout << "\n\nSorted list:\n";
for (int i = 0; i < DAYS; i++)
cout << arrweek[i] << endl;
cout << endl;
return 0;
}
void bsort(char** arr, const int n)
{
int i, j;
for (i = 0; i < n-1; i++)
for (j = i+1; j < n; j++)
order(arr+i, arr+j);
}
void order(char** day1, char** day2)
{
if ( (strcmp( (*day1), (*day2))) > 0 ) //<-- THIS is kind of weird...
{
char* temp = *day1;
*day1 = *day2;
*day2 = temp;
}
}
In that line of code, I was expecting to have to dereference one more level to get to the string contained by the pointer being pointed to....much to my surprise (read: dismay) I only had to dereference one level to make () work...wait a second! Does that mean that strcmp() accepts pointers as arguments and I really only had to pass the addresses of the strings I need compared, not the strings themselves? Please tell me I'm right...after a whole night of being wrong, that would make things look much brighter...