0

This is the code

#include <iostream>

int main(){

    const char* message{"Hello world."};
    std::cout << "message : " << message << std::endl;

    //*message = 'B'; //compiler error
    std::cout << "*message : " << *message << std::endl;

    //Allow users to modify the string
    const char message1[]{"Hello world"};
    message1[0] = 'B';

    return 0;
}

I don't really see any difference between them and in which situation one or the other can be apply.

Lasty, How do we print out the address of pointer initialized with string?

康桓瑋
  • 33,481
  • 5
  • 40
  • 90
  • 1
    The code snippet actually demonstrates the differences. What is confusing about it? – ShadowRanger May 16 '22 at 02:42
  • 1
    `message1[0] = 'B';` won't compile, you can't change `message1`. – François Andrieux May 16 '22 at 02:44
  • @FrançoisAndrieux: I feel like maybe they (or whoever who made the snippet) made a mistake copying a guide to the differences when the array is non-`const`, but yeah, the snippet as written is wrong. – ShadowRanger May 16 '22 at 02:46
  • The duplicate I linked is the C duplicate, but aside from the whole "C string literals are technically not `const`, but modifying them is undefined so they may as well be `const`", the info is the same. Having trouble finding the C++-specific duplicate (which I'm sure exists). – ShadowRanger May 16 '22 at 02:47
  • To print the address, use something like ``std::cout << static_cast(message)``. (I think that part of the question is not addressed in the linked answer.) – Christian Halaszovich May 16 '22 at 02:49

0 Answers0