C++ STRINGS CONCATENATION USING POINTERS | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula gr√°tis
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; }

11th Jan 2021, 10:22 PM
Hammad Yaqub
Hammad Yaqub - avatar
4 Respostas
+ 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>.
11th Jan 2021, 11:53 PM
Ipang
+ 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.
11th Jan 2021, 11:58 PM
rodwynnejones
rodwynnejones - avatar
+ 1
So in the second loop , *pString1 = *pString2 , *pString Is pointing ti the null char of string 1 right?
12th Jan 2021, 12:19 AM
Hammad Yaqub
Hammad Yaqub - avatar
0
I know that It puts automaticly the null char
12th Jan 2021, 12:20 AM
Hammad Yaqub
Hammad Yaqub - avatar