* is the 'indirection operator'.
When you say
char* ptr;
you are setting aside a piece of memory called 'ptr' in which to store the location of a character.
When I say:
char* ptr = "Some text";
I am storing the location of the FIRST character of the string "Some Test" in the memory location called 'ptr'.
So ptr holds the location of the FIRST character of the sequence of characters which make up my string.
If I want to make ptr 'point' to the location of a different string I would say this:
ptr = "New text";
So by modifying ptr alone I modify the particular area of memory that it points to.
So what if I want to modify the string itself? What if I want to change the characters of the string rather than make my ptr point to a different one?
Then I use *
If I want to EXAMINE the actual character that ptr points to I say *ptr. It means "go to the address in memory recorded in the variable ptr and give me the character stored there".
For example:
1 2 3
|
char* ptr = new char[10]; // give ptr the location of 10 characters
*ptr = 'M'; // set the first character to the letter M
|
If you want to set the second character then you have to add 1 to the value of ptr to move the access to the next memory location up:
|
*(ptr + 1) = 'r'; // set the second character to the letter r
|
and
|
*(ptr + 2) = ' '; // set the third character to a space
|
and
|
*(ptr + 3) = 'X'; // set the fourth character to the letter X
|
By convention when you place a string of characters directly in memory like this you need to make the last character a zero 0.
|
*(ptr + 4) = 0; // set the fifth character 0 to end the string.
|
Of course its better to use the ready made function to do all this for you:
1 2 3
|
char* ptr = new char[10]; // give ptr the location of 10 characters
strcpy(ptr, "Mr X"); // copy the string "Mr X" into the memory beginning at ptr.
|