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:

  1. We include the iostream library, which allows us to use input/output functions.
  2. We use the using namespace std; statement to avoid typing std:: before standard library functions.
  3. We define the main function, which is the entry point of the program.
  4. We declare a character array source and initialize it with the string "Hello, world!".
  5. 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.
  6. We declare two character pointers srcPtr and destPtr and initialize them with the addresses of source and destination, respectively.
  7. We enter a while loop that continues until the end of the source string is reached (*srcPtr != '\0').
  8. Inside the loop, we assign the value of the character pointed to by srcPtr to the character pointed to by destPtr (destPtr = srcPtr).
  9. We increment both srcPtr and destPtr to move to the next characters in the source and destination strings.
  10. After the loop, we assign the null character ('\0') to the last character of the destination string to mark its end.
  11. We print the copied string using the cout statement.
  12. Finally, we return 0 to indicate successful program execution.