Write C++ program to copy one string to another string using pointers
#include <iostream>
using namespace std;
int main() {
char source[] = "Hello, world!";
char destination[50];
char *srcPtr = source;
char *destPtr = destination;
while (*srcPtr != '\0') {
destPtr = srcPtr;
srcPtr++;
destPtr++;
}
*destPtr = '\0';
cout << "Copied string: " << destination << endl;
return 0;
}
Explanation:
- We include the
iostream
library, which allows us to use input/output functions. - We use the
using namespace std;
statement to avoid typingstd::
before standard library functions. - We define the
main
function, which is the entry point of the program. - We declare a character array
source
and initialize it with the string "Hello, world!". - We declare another character array
destination
to store the copied string. It has a size of 50 to ensure it can hold the copied string. - We declare two character pointers
srcPtr
anddestPtr
and initialize them with the addresses ofsource
anddestination
, respectively. - We enter a
while
loop that continues until the end of the source string is reached (*srcPtr != '\0'
). - Inside the loop, we assign the value of the character pointed to by
srcPtr
to the character pointed to bydestPtr
(destPtr = srcPtr
). - We increment both
srcPtr
anddestPtr
to move to the next characters in the source and destination strings. - After the loop, we assign the null character (
'\0'
) to the last character of the destination string to mark its end. - We print the copied string using the
cout
statement. - Finally, we return 0 to indicate successful program execution.