I am greatly surprised with that line of code.
This is how I interpret it "Pointer of char 'SampleCharacters' points to address of "Hello"".
How does 'SampleCharacters' accepts the address of "Hello" even though it is a literal string?
If I do this I receive a syntax error
int* P_SampleInteger = 13;
or
char* P_AnotherSampleCharacter = 'a';
English isn't my native language sorry.
Thanks in advance.!
It is more correct to write this as a pointer to const char:
constchar* P_SampleCharacter = "Hello";
How does 'SampleCharacters' accepts the address of "Hello" even though it is a literal string?
It's a feature. The "Hello" string literal will be stored (probably) in a read-only segment of the program's memory. And because it's basically an array of char, you can take its memory address.
This doesn't work with non-arrays literals because the optimizer can possibly remove them from the program completely.
Here's a C program (C99 standard) to show how you can do something similar for non-char arrays.
Unfortunately this relies on a feature of the C language that C++ doesn't have yet, named compound literals.
P_Anything
Address of 'P_Anything': 004FFB78
Value its holding: a╠╠╠╠╠╠╠╠o√O
Value(*): a
Character
Address of 'Character': a╠╠╠╠╠╠╠╠o√O
Value its holding: a
Try 'P_Anything' to hold the address of 'AnotherCharacter'
P_Anything
Address of 'P_Anything': 004FFB78
Value its holding: b╠╠╠╠╠╠╠╠╠╠╠a╠╠╠╠╠╠╠╠c√O
Value(*): b
AnotherCharacter
Address of 'AnotherCharacter': b╠╠╠╠╠╠╠╠╠╠╠a╠╠╠╠╠╠╠╠c√O
Value: b
Try 'P_Anything' to hold again the previous address
P_Anything
Address of 'P_Anything': 004FFB78
Value its holding: a╠╠╠╠╠╠╠╠o√O
Value(*): a
Character
Address of 'Character': a╠╠╠╠╠╠╠╠o√O
Value its holding: a
I tried to create a simple program to understand more about this.
It seems that if I let the pointer to hold another address,it is just appending the address of the assigned address to the address that the pointer currently pointing.
There is another question raised on my mind. May you please guys give a real world usage of char* foo = "boo";
I will research more about this topic. Thanks peter and cat. :D
It seems that if I let the pointer to hold another address,it is just appending the address of the assigned address to the address that the pointer currently pointing.
No. Also pay attention, we told you twice to use a const pointer and you are ignoring that.
C style strings (char arrays) are NUL-terminated. This means that a string like "dog" contains four characters: 'd', 'o', 'g' and 0 (which is called NUL).
So when you print the contents of a pointer to char, the contents are printed until a value of 0 is found. In your case, you see how 'a' and 'b' are situated in memory and you also see what's in between them.