Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the definition of ++p where p is const char *p in C?

Tags:

c

pointers

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:

  • Does it tests, at every loop, if (*p != null) ?
  • If it does 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?
like image 859
Francesco Bonizzi Avatar asked Dec 04 '22 03:12

Francesco Bonizzi


1 Answers

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

like image 153
Giorgi Moniava Avatar answered Dec 20 '22 09:12

Giorgi Moniava