String Literals using Pointers in C++

String literals in C++ are sequences of characters enclosed in double quotes. When a string literal is encountered in a C++ program, it is automatically converted into a null-terminated character array, with an additional null character (‘\0’) appended at the end to mark the end of the string.

Pointers in C++ are variables that store memory addresses. They can be used to point to various types of data, including strings.

In C++, string literals are stored in read-only memory, and their addresses can be obtained using pointers. By using pointers, you can manipulate and access string literals in different ways.

Example Program:

#include <iostream>

int main() {
    // Define a string literal
    const char* str = "Hello, world!";

    // Print the string using pointer
    std::cout << "String: " << str << std::endl;

    // Access individual characters using pointer arithmetic
    std::cout << "First character: " << *str << std::endl;
    std::cout << "Second character: " << *(str + 1) << std::endl;

    // Print the string character by character
    std::cout << "Characters: ";
    for (int i = 0; str[i] != '\0'; ++i) {
        std::cout << *(str + i);
    }
    std::cout << std::endl;

    return 0;
}

Line by Line Explanation:

  • Line 3: Main function begins.
  • Line 5: Define a pointer str of type const char* and initialize it with the address of the string literal "Hello, world!". The const qualifier is used to indicate that the string literal is stored in read-only memory and should not be modified.
  • Line 8: Print the entire string using the pointer str.
  • Line 11-12: Access and print the first and second characters of the string using pointer arithmetic. The expression *(str + i) is equivalent to str[i], where i is the index of the character.
  • Line 15-21: Print each character of the string one by one using a loop. The loop iterates over each character of the string until it encounters the null character '\0', which marks the end of the string.

In this program, we demonstrate how to use pointers to work with string literals in C++. We access individual characters of the string using pointer arithmetic and print the entire string character by character using a loop.