
Pointers to Pointers to Char in C
Quote:
> Hi everyone...
> I'm a student of C and I'm confused about this question involving
> pointers.
> In the following code I'm confused about what d points to. Here's my
> (obviously wrong) thinking...
Be careful here. All these initialization of b, c, d are to non-constants.
This is a dangerous road to start down.
Let's look at a modified form of your code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char a[] = "Tintern Abbey";
char *b = a + 3;
char **c = &b;
char *d = *c;
printf("a is %p; the string is %s\n", (void *)a, a);
printf("b is %p; the string is %s\n", (void *)b, b);
printf("c is %p; *c is %p; the string is %s\n",
(void *)c, (void *)*c, *c);
printf("d is %p; the string is %s\n", (void *)d, d);
printf("d+5 is %p; the string is %s\n", (void *)(d+5), d+5);
puts(d + 5);
return 0;
Quote:
}
The values of the pointers will obviously be different for you, but they are
useful for explication. I get the following.
a is 2e0fd0; the string is Tintern Abbey
b is 2e0fd3; the string is tern Abbey
c is 2e0fcc; *c is 2e0fd3; the string is tern Abbey
d is 2e0fd3; the string is tern Abbey
d+5 is 2e0fd8; the string is Abbey
Abbey
Quote:
> b is a pointer to char which points to the 4th char of array a[]... ('t');
==
OK:
a is 2e0fd0; the string is Tintern Abbey
b is 2e0fd3; the string is tern Abbey
==
Quote:
> c is a pointer to a pointer to char which is assigned the address
> of b...so it holds the address of b. So c points to b.
==
OK:
b is 2e0fd3; the string is tern Abbey
c is 2e0fcc; *c is 2e0fd3; the string is tern Abbey
==
Quote:
> Then we come to my problem: *d = *c. It seems to say that d (which
> is a pointer to char) is assigned the dereferenced value of c. In
> other words, it would seem that d and c both point to b.
==
No ...
b is 2e0fd3; the string is tern Abbey
c is 2e0fcc; *c is 2e0fd3; the string is tern Abbey
d is 2e0fd3; the string is tern Abbey
c points to b; d is a pointer with the same value as b (*c).
==
Quote:
> But running the program prints "Abbey" which means that d points to
> 't' and d+5 is the string "Abbey" which means that d doesn't point to
> b but points to the SAME address that b does.
> HELP!! Thanks...Stephen. ;>)
> #include <stdio.h>
> #include <stdlib.h>
> #include <string.h>
> main()
> {
> char a[] = "Tintern Abbey";
> char *b=a+3;
> char **c=&b;
> char *d=*c;
> puts(d +5);
> }
> --
> *
> *-|-* Stephen Levinson
> *-|-*
> *
> --
--
--