0
C++ STRINGS CONCATENATION USING POINTERS
Hi guys , I have a little problem , I didnt understand this code. In particular I didnt understand the 2 whiles in the code and the third-last line of the code *pString1 = '\0' I didnt undersatnd what they do... Can anyone explain me this code, please? #include <iostream> using namespace std; int main() { char string1[20], string2[20], * pString1, * pString2; cout << "Enter the first string: "; cin >> string1; cout << "Enter the second string: "; cin >> string2; pString1 = string1; pString2 = string2; while (*pString1 != '\0') { pString1++; } while (*pString2 != '\0') { *pString1 = *pString2; pString1++; pString2++; } *pString1 = '\0'; cout << string1; }
5 Answers
+ 5
Just as an FYI, the code shows example using C string (char arrays) not really C++ string.
The first loop shifted pointer <pString1> to point to the end of <string1>.
The second loop copies all characters from <string2>, into <string1>, indirectly through the use of pointers <pString1> and <pString2>.
*pString1 = *pString2;
pString1++;
pString2++;
Acts much like
string1[x] = string2[y];
x++;
y++;
*pString1 = '\0';
Puts string terminator (null character) into <string1> indirectly through pointer <pString1>.
WARNING:
Care needs to be taken using this approach. Risk to overrun the <string1> buffer is present when length of <string1> + length of <string2> exceeds length of <string1>.
+ 2
The first while loop increments the pointer until it finds the end of string1, so now.... the pointer points to the end of string1.
In the second loop, string2 is "appended" to end of string1 one character at a time.
Then...a '\0' (null character) is appended to mark the end of the string.
+ 1
So in the second loop , *pString1 = *pString2 , *pString Is pointing ti the null char of string 1 right?
0
I know that It puts automaticly the null char