p
is a pointer to char
. Therefore, dereferencing it with *p
yields
a char
.
Adding 1 to p
moves it to the next character in whatever string you’re
traversing. Adding 1 to *p
adds one to the character p
is pointing
to.
Let’s go through each of your tries and see what’s wrong with it.
char* hello = "Hello, world!";
The common part: hello
is a pointer to char
, and it is pointing to a
constant string that the compiler will embed somewhere in the object
file. Note that such a string should not be changed; you will often get
an error for doing so.
If you want a string you can change, char hello[] = "Hello, world!";
works; this creates a buffer as a local variable that can be freely
manipulated.
for( char* p = hello; p!=0; p++ ) printf("%x\n", p);
Here, you correctly point p
at the first character of hello
.
However, you then look for the end of the string by comparing p
to
zero. p
is a pointer, and 0 as a pointer means a NULL pointer.
for( char* p = &hello; p!=0; p++ ) printf("%x\n", p);
Here, you point p
at the address of hello
, meaning wherever the
process is storing the pointer known as hello
. Dereferencing this will
give you hello
, not what it points to.
for( char* p = *hello; p!=0; p++ ) printf("%x\n", p);
Here, you dereference hello
, giving a char
with a value of H
.
Assigning this to p
is a type mismatch and semantically incorrect as
well.
for( char* p = hello; *p!=0; *p++ ) printf("%x\n", *p);
Here, at last, you correctly compare what p
points to, to zero.
However, you also increment *p
instead of p
, which is incorrect,
and also (as mentioned above) will cause problems with a constant string
such as this one.
*p++
will increment p
as well, returning what p
pointed to before
the increment, which is moot since it isn’t used.
One other thing: do you want to print the value of the pointer p
, or
the char
it’s pointing to? The first three print the pointer
correctly. The last one uses %x
to print the char
. Not sure what
that will do, but it won’t be correct.
Since you used %x
, I assume you want to print the character itself in
hex? That would be printf("%x\n", *p);
as in the last one. However, I
would recommend %02x
to get a constant width with zero-padding.
Assuming you want to print the character, here’s a correct version:
for( char* p = hello; *p!=0; p++ ) printf("%x\n", *p);
Or, since 0
is false, we can say more briefly and idiomatically:
for( char* p = hello; *p; p++ ) printf("%x\n", *p);