Thread: char *ptr

  1. #1
    Registered User
    Join Date
    Mar 2017
    Posts
    1

    char *ptr

    Declared char array (read-only):
    const char alpha [] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    Given a char pointer called ptr and the alpha array declared above, how can I make ptr point to the letter 'D'?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Nefisto
    Here we get the mem position of the const char, and made an implicity conversion for (char*) to remove const properties, after we use * to get the value that is storaged in this mem position
    You used an explicit conversion by doing the type cast, not an implicit conversion (which by definition would not involve the type cast notation).

    Quote Originally Posted by Nefisto
    this another one will be usefull if u want to change the value of an const vector
    Don't do that! If something started off being declared const, attempting to change its value results in undefined behaviour. In fact, ptr should not even be a pointer to non-const char, i.e., while this is correct, it is poor practice:
    Code:
    char* ptr = NULL;
    
    ptr = (char*)alpha;
    It would be better to declare ptr to be a pointer to const char instead, and hence write:
    Code:
    const char *ptr = alpha;
    This way, one would not accidentally attempt to modify the array of const char through ptr because something like this:
    Code:
    *ptr = '@';
    would result in an error or at least a warning from your compiler.

    Generally, if you are casting away const-ness, it is because you know for sure that the underlying object is non-const, so you are just trying to say, eliminate a harmless const to non-const implicit conversion warning because of some API that you are working with.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 09-25-2014, 06:12 AM
  2. Replies: 2
    Last Post: 09-25-2014, 04:03 AM
  3. Replies: 4
    Last Post: 07-24-2012, 10:41 AM
  4. undefined reference to `RunSwmmDll(char*, char*, char*)'
    By amkabaasha in forum C++ Programming
    Replies: 1
    Last Post: 10-31-2011, 12:33 PM
  5. Assigning Const Char*s, Char*s, and Char[]s to wach other
    By Inquirer in forum Linux Programming
    Replies: 1
    Last Post: 04-29-2003, 10:52 PM

Tags for this Thread