|
|
|||||||||
|
|||||||||
|
|||||||||
| |
||
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
C++ pointer problem
Can anyone that is very familiar with C++ pointers help me with this? I’m about to tear out my hair…
Below is the program on pg. 191 of the book: “C++, A Beginner’s Guide, 2nd Edition.” by Herbert Schildt. I only added in some new line statements for the sake of output neatness and the statement “system(PAUSE)” out of necessity, so after compiling, my output screen wouldn’t disappear immediately. #include <iostream> using namespace std; char *get_substr(char *sub, char *str); int main() { char *substr; substr = get_substr("three", "one two three four"); cout << "substring found: " << substr; cout << '\n' << '\n' ; system("PAUSE") ; return 0 ; } char *get_substr(char *sub, char *str) { int t; char *p, *p2, *start ; for(t=0; str[t]; t++) { p = &str[t] ; start = p ; p2 = sub ; while(*p2 && *p2 == *p) { p++ ; p2++ ; } if(!*p2) return start ; } return 0; } And here are the results of the program: substring found: three four My question is this, why is the value returned by the character pointer “start” all of a sudden pointing at the character “t” in the string “three” from the full character string “one two three four”, that is being pointed to by character pointer “str” ? It looks like before passing the address of character pointer “start” back to the calling function after the sub string is found in function “*getsubstr“, character pointer “start” should be pointing at the null in between the words “three” and “four”of char pointer “str”, since pointer “p”’s memory address has been advanced in unison with “p2”, in order to get to the end of the string that “p2” is pointing to (since p2 is equal to sub). That would be the only way it seems to me like the while statement could be exited. The string pointed to by “p2” should be at the null after the string “three”, and “p” should be at the null after the sub string “three” of the full string “one two three four” that it is pointing to. This is very confusing and if anyone can show me how to work through this program step by step I’d appreciate it big time. I was just about to pat myself on the back after getting through this book this far without hitting any brick walls until I ran smack dab in to this one. -- F.David Carter |
![]() |
| Viewing: ASP Free Forums > Other > Programming Help > C++ pointer problem |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|