February 23rd, 2003, 12:12 AM
* when initializing constand char?
I don't understand what the * does in:
const char *whatever = "Hello this is a whatever program";
I took it out and the program won't run, I was just wondering what the hell that is needed for. It gives no description in my book, it isn't even in the god damn declaring constants section! :mad:
February 23rd, 2003, 03:17 AM
Try looking in the pointer section. You also may want to get another book to cross reference troublesome problems. I can recommend Ivor Horton's Beginning C++ 6.
The "*" denotes a pointer. You can't assign a string of characters to a variable declared like this:
const char whatever;
Both "a_character" and "whatever" being of type char will only hold one character(and you have to use single quotes in the assignment statement). In the case of "whatever", it's declared constant, so you can't try to change its value later. On the other hand, an array of type char can hold a string of characters:
char some_text="This is the way to do it.";
and a pointer to type char (char*) can also hold a string of characters:
char* pwords="You can do it this way too.";
With both cases you can output the string using only the name:
Normally, if you try to print out a pointer like in the last line of code, the output will be an address in memory because pointers store addresses. However, pointers to type char are an exception: cout handles them differently and outputs the whole string.(Note: an array name is actually a pointer too.)
Last edited by 7stud; February 23rd, 2003 at 06:03 AM.
February 23rd, 2003, 03:30 AM
February 23rd, 2003, 11:19 AM
that article was great..its a great site to! Thanks! and thanks stud..you also explained it very well.
February 23rd, 2003, 03:08 PM
Here's a technical point:
With pwords declared like this:
it looks like the value in memory that pwords points to is not constant: its a pointer to type char after all not a pointer to type const char. However, a string literal at some point became constant in C++, so you cannot try and change it like this:
pwords = "You can't try and change this string."
That will compile, but you will get an error when you run your program. So, my book suggests declaring the pointer like this in the first place to keep you from possibly trying to change its value:
const char* pwords;
That declares pword as a pointer to a const char. Then it's obvious you cannot try and change the value pwords points to, and if you do try and change it accidentally, the compiler will find the error.
Last edited by 7stud; February 23rd, 2003 at 03:11 PM.