Newbie question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • konijn_
    Hellband maintainer
    • Jul 2007
    • 367

    Newbie question

    In my usual passive aggresive way I smack down in one thread and humbly ask for help in another

    So,

    Code:
    /* Check for entering a dungeon */
    if ((p_ptr->visits & (0x1 << dun_level)) == 0)
    {
      const char *msg = NULL;
    
    if (dun_level == 0)
      msg = "You enter the sewers of Volterra.";
    else if (dun_level == 1)
      msg = "You descend into the lower levels of Hell.";
    else if (dun_level == 10)
      msg = "You descend into the circle of the Heretics."
    ...
    msg_print(msg);
    ;

    Could this code crash at any moment ? I seem to be putting a string in a pointer that points to one char only ?? What would be the proper way of doing this without jumping through hoops to make the msg_print work ?

    T.
    * Are you ready for something else ? Hellband 0.8.8 is out! *
  • d_m
    Angband Devteam member
    • Aug 2008
    • 1517

    #2
    Assigning a string literal to a "const char*" is a perfectly fine thing to do.

    Your pointer (const char *msg) points to an address in memory. Your string constants will all initialize the necessary amount of memory (length + 1). Thus, your pointer does not point to "one character" but rather "an address whose offsets are character-length."
    linux->xterm->screen->pmacs

    Comment

    • zaimoni
      Knight
      • Apr 2007
      • 590

      #3
      Originally posted by konijn_
      In my usual passive aggresive way I smack down in one thread and humbly ask for help in another

      So,

      Code:
      /* Check for entering a dungeon */
      if ((p_ptr->visits & (0x1 << dun_level)) == 0)
      {
        const char *msg = NULL;
      
      if (dun_level == 0)
        msg = "You enter the sewers of Volterra.";
      else if (dun_level == 1)
        msg = "You descend into the lower levels of Hell.";
      else if (dun_level == 10)
        msg = "You descend into the circle of the Heretics."
      ...
      msg_print(msg);
      ;

      Could this code crash at any moment ?
      No, you live. msg_print is pleased.
      Originally posted by konijn_
      I seem to be putting a string in a pointer that points to one char only ?
      The pointer doesn't care about how many characters follow the one it's pointing to. As long as it's NUL-terminated before the valid memory ends, it's fine -- and this is always true for string constants.
      Zaiband: end the "I shouldn't have survived that" experience. V3.0.6 fork on Hg.
      Zaiband 3.0.10 ETA Mar. 7 2011 (Yes, schedule slipped. Latest testing indicates not enough assert() calls to allow release.)
      Z.C++: pre-alpha C/C++ compiler system (usable preprocessor). Also on Hg. Z.C++ 0.0.10 ETA December 31 2011

      Comment

      Working...
      😀
      😂
      🥰
      😘
      🤢
      😎
      😞
      😡
      👍
      👎