PDA

View Full Version : Newbie question


konijn_
December 4, 2009, 00:40
In my usual passive aggresive way I smack down in one thread and humbly ask for help in another :D

So,

/* 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.

d_m
December 4, 2009, 04:47
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."

zaimoni
December 5, 2009, 02:00
In my usual passive aggresive way I smack down in one thread and humbly ask for help in another :D

So,

/* 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.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.