| TIP: Click on subject to list as thread! | ANSI |
| echo: | |
|---|---|
| to: | |
| from: | |
| date: | |
| subject: | Pointers & Strings |
FT> pB = strB; /* point pB at string B */
FT> while(*pA != '\0') /* line A (see text) */
FT> {
FT> *pB++ = *pA++; /* line B (see text) */
^^^^^
FT> }
Notice how we're moving pB to the next value each time through this while loop.
FT> What I have a hard time figuring out is the reason
FT> why I can't replace (strB) with (pB) in the
FT> following line since pB points at string B:
FT> puts(strB); /* show strB on screen */
When the loop is done, pB no longer points at strB, but at the
"end" of strB!
FT> If I re-point at strB:
FT> pB = strB; /* point pB at string B */
FT> just above:
FT> puts(pB); /* show what pB is pointing to */
FT> then the string is printed out!!!
Right - you changed where pB is pointing at, moving back to where it
started before the loop.
FT> Why do I have to point to string B a second time? Once
FT> a pointer points to a specific address, doesn't it
FT> reflect whatever value is stored at this address as
FT> long as types match?
True - but if you try printing out where the pointer is pointing at, you'll
notice it change.
FT> #include
FT> char strA[80] = "A string to be used for demonstration purposes";
FT> char strB[80];
FT> int main(void)
FT> {
FT> char *pA; /* a pointer to type character */
FT> char *pB; /* another pointer to type character */
FT> puts(strA); /* show string A */
FT> pA = strA; /* point pA at string A */
FT> puts(pA); /* show what pA is pointing to */
FT> pB = strB; /* point pB at string B */
FT> putchar('\n'); /* move down one line on the screen */
printf("pB is now at %p\n", (void*)pB);
printf("Coincidentally, strB is also at %p\n", (void*)strB);
FT> while(*pA != '\0') /* line A (see text) */
FT> {
FT> *pB++ = *pA++; /* line B (see text) */
FT> }
printf("After while loop, pB is at %p\n", (void*)pB);
printf("This is a difference of %d\n", pB - strB);
printf("Coincidentally, the string below's length is %d!\n\n",
strlen(strB));
FT> *pB = '\0'; /* line C (see text) */
FT> puts(strB); /* show strB on screen */
FT> return 0;
FT> }
Hope this helps!
---
* Origin: Tanktalus' Tower BBS (1:250/102)SEEN-BY: 396/1 622/419 632/371 633/260 267 270 371 634/397 635/506 728 SEEN-BY: 639/252 670/213 218 @PATH: 250/102 201 99 396/1 633/260 635/506 728 633/267 |
|
| SOURCE: echomail via fidonet.ozzmosis.com | |
Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.