Also, to bring up the point the title entails:
What is the different between string and char* in C++ |
A string is a sequence of characters. A
char* myChar
declaration declares myChar to point to one (or more) characters, depending on its usage.
Consider the following example:
1 2 3 4 5
|
char* a;
string str = "test";
a = &str[0];
cout << a;
getchar();
| |
Line 3 assigns the address of the first character in the sequence of characters 'str' to my pointer, 'a'. Printing 'a' will print that character (the first of the sequence), as well as all others until the null terminator char, '\0'.
Now see:
1 2 3 4 5
|
char* a;
string str = "test";
a = &str[1];
cout << a;
getchar();
| |
Note that part of the 'str' is cut off. This is because 'a' now references the character after the first character in the str. (The offset of 1, not 0).
Now, we can try:
1 2 3 4 5
|
char* a;
string str = "test";
a = &str[0];
cout << a[1];
getchar();
| |
where cout << a[index] prints the character in the array of characters at position 'index'.
These examples may not have been as clear as they come, but I hope they help.