Click to See Complete Forum and Search --> : a q about strings an '\0' in c


Sidey
12-27-2000, 12:19 PM
This is part of a function that I'm using to get item names. So get_item_name("RACE01") returns "Human", but do I need to retuen "Human\0" as its a pointer ? (I still don't understand those pesky pointers fully). Also, is this the best way to write a function like this ?

cheers for any help


char *get_item_name(char *item)
{
/* races */
if (strcmp(item, "RACE01") == 0) {
return "Human";
}
if (strcmp(item, "RACE02") == 0) {
return "Elf";
}
if (strcmp(item, "RACE03") == 0) {
return "Half Elf";
}
if (strcmp(item, "RACE04") == 0) {
return "Gnome";
}
if (strcmp(item, "RACE05") == 0) {
return "Halfling";
}
if (strcmp(item, "RACE06") == 0) {
return "Dwarf";
}
if (strcmp(item, "RACE07") == 0) {
return "Half Orc";
}
else
return "ERROR";
}

jemfinch
12-27-2000, 12:30 PM
C automatically sticks a null byte at the end of literal strings.

With that said, the way you're doing what you're doing is definitely the wrong way. If you're going to keep an object's identity in a string (which may be inadvisable in the first place) you might as well store "Half Elf" in it rather than "RACE03". There's no reason for that extra level of indirection. And it's slow.

I would store the object's identity in an int, and then #define RACE03 to some number; then I could use a simple switch statement to turn the numbers into the string representation of an object. I would do this for two reasons: firstly, comparisons between strings are slow; secondly, someone might later want to port my game to a language other than english.

Jeremy

Sterling
12-27-2000, 01:04 PM
Even better - have something like the following:

#define MAXRACES 5
char *races[5] = {"Human", "Elf", "Half-Elf", ...};
int race;
/* .... */


So you get the benefits of having a numeric race (faster comparisons, etc) and you still get a fast name lookup. To get a race's name, you'd just do: races[race]

Hope that wasn't TOO confusing...


------------------
-Sterling
-This post made with the Lizard! (http://www.mozilla.org)

jemfinch
12-27-2000, 04:09 PM
Originally posted by Sterling:

#define MAXRACES 5
char *races[5] = {"Human", "Elf", "Half-Elf", ...};
int race;
/* .... */



Great idea, but I think you meant for that declaration to be "char *races[MAXRACES]" http://www.linuxnewbie.org/ubb/smile.gif

Jeremy

Sidey
12-28-2000, 09:33 AM
Cheers for the help http://www.linuxnewbie.org/ubb/smile.gif

Sterling
12-28-2000, 10:48 AM
Jemfinch - Whoops! My mistake! http://www.linuxnewbie.org/ubb/frown.gif

Of course, static arrays in C/C++ are fairly limited, but they're still useful.

------------------
-Sterling
-This post made with the Lizard! (http://www.mozilla.org)