If I need to iterate over an array in C, I can do something like:
void uselessTest(const char *p)
{
while(*p)
{
++p;
}
}
I'm wondering about what that means in detail:
if (*p != null)
?p = p + 1
, what does that mean? Is p a numeric value? *p
should be the value pointed and p
the address of the pointer? So in this loop p
changes while *p
remains the same?Does it tests, at every loop, if (*p != null) ?
I would say more correct is to say it checks if *p!=0
.
If it does p = p + 1, what does that mean? Is p a numeric value?
It appears C standard does not define what pointer is internally. But in below example, I will assume p holds an address represented as integer (which usually is the case). In that case, in your above example, when you add one to it, p
moves to the next
address, e.g., if p
was 0x1000, after increment it would become 0x1001 (This is because size of char
is 1, in case p
was pointer to int
it would move four bytes forward* -given size of integer is four).
So in this loop p changes while *p remains the same?
No, indeed *p
tries to dereference p
, in other words, obtain contents of the object stored at address p
. So of course if you change value of p
, you may also get different content at new address. e.g., if initial value of p
was 0x1000, after increment, it will be 0x1001, and *p
will try to read value at 0x1001 which might be different from value stored at 0x1000.
* Look up pointer arithmetic for more details about that
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With