I've been reading C++ for dummies lately and either the title is a misnomer or they didn't count on me. On a section about utilizing arrays of pointers with characters strings they show a function on which I've been completely stumped and don't know where to turn.
char* int2month(int nMonth)
{
//check to see if value is in rang
if ((nMonth < 0) || (nMonth > 12))
return "invalid";
//nMonth is valid - return the name of the month
char* pszMonths[] = {"invalid", "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
return pszMonths[nMonth];
}
First of (but not the main question), I don't understand why the return type is a pointer and how you can return pszMonths without it going out of scope. I've read about it in this book and online but I don't get it in this example.
The main question I have is "how does this work?!?!". I don't understand how you can create an array of pointers and actually initialize them. If I remember correctly you can't do this with numeric data types. Is each pointer in the "array of pointers" like an array itself, containing the individual characters which make up the words? This whole thing just boggles my mind.
August 20 - Since there seems to me some confusion by the people trying to help me at as to where my confusion actually stems from I'll try to explain it better. The section of code in particular I am concerned with is the following:
//nMonth is valid - return the name of the month
char* pszMonths[] = {"invalid", "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
I thought that when you made a pointer you could only assign it to another predetermined value. I'm confused that what seems to be an array of pointers (going by the book here) initializes the month names. I did not think pointers could actually initialize values. Is the array dynamically allocating memory? Is "invalid" essentially equivalent to a "new char;" statement or something similar?
I'll try re-reading the posts in case they answered my questions but I just didn't understand the first time around.