Skip to main content
gamedev.net
🔒 Locked

help with string debugging

Started by mjs1 Dec 27, 2004 at 11:11 PM 2 replies 500+ views
Original Post
mjs1
mjs1
Hello! I'm attempting to increment a char pointer through a string, evaluating the character the char pointer is currently pointing to. When run, it appears the string pointer never reaches the '\0' character I expect to be at the end of the string. Since this is the test for when the "for" loop incrementing through the characters of the string should exit, I run into problems, and the char pointer starts pointing to all sorts of weird things. Here's a short test program that shows the problem: #include #include using namespace std; void produceString(char *iString) { for (char *tString = iString; tString != '\0'; tString++) { cout << tString << endl; } } int main(int argc, char** argv) { produceString("F"); return 0; } Any help would be greatly appreciated!
Prototype
Prototype
The problem is in here:
for (char *tString = iString; *tString != '\0'; tString++)

You should dereference the char* to get the actual char it is pointing to. Otherwise you are comparing the whole string to a char which obviously will never be true.

Edit: fixed some tags
mnansgar
mnansgar
tString is defined as a POINTER to a char (ie "char *"). Thus, if I make the following initializations:

char *tString = iString;
char newChar = tString;

Then I'll get a compiler error! Remember that if I simply refer to "tString", I receive an ADDRESS (typically a 32-bit value) specifying where a certain VALUE, in this case the value of the first character in iString, is stored. If I refer to "*tString" (apply the dereference operator to the pointer variable), then I receive the contents of what is stored at the address stored in tString. Thus, instead of the comparison "tString != '\0'", you need "*tString != '\0'" to compare the CONTENTS of what is stored at the address stored in the pointer tString.
h20, member of WFG 0 A.D.
mjs1
mjs1
Thank you very much! Everything's working fine now!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.