Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not Understanding Pointer Arithmetic with ++ and --

So, I am learning about pointers via http://cplusplus.com/doc/tutorial/pointers/ and I do not understand anything about the pointer arithmetic section. Could someone clear things up or point me to a tutorial about this that I may better understand.

I am especially confused with all the parentheses things like the difference between *p++,(*p)++, *(p++), and etc.

like image 621
VinylScratch Avatar asked Nov 21 '11 16:11

VinylScratch


2 Answers

*p++

For this one, ++ has higher precedence then * so it increments the pointer by one but retrieves the value at the original location since post-increment returns the pointer and then increments its value.

(*p)++

This forces the precedence in the other direction, so the pointer is de-referenced first and then the value at that location in incremented by one (but the value at the original pointer location is returned).

*(p++)

This one increments the pointer first so it acts the same as the first one.

An important thing to note, is that the amount the pointer is incremented is affected by the pointer type. From the link you provided:

char *mychar;
short *myshort;
long *mylong;

char is one byte in length so the ++ increases the pointer by 1 (since pointers point to the beginning of each byte).

short is two bytes in length so the ++ increases the pointer by 2 in order to point at the start of the next short rather than the start of the next byte.

long is four bytes in the length so the ++ increases the pointer by 4.

like image 146
N_A Avatar answered Sep 25 '22 03:09

N_A


I found useful some years ago an explanation of strcpy, from Kernighan/Ritchie (I don't have the text available now, hope the code it's accurate): cpy_0, cpy_1, cpy_2 are all equivalent to strcpy:

char *cpy_0(char *t, const char *s)
{
    int i = 0;
    for ( ; t[i]; i++)
        t[i] = s[i];
    t[i] = s[i];
    i++;
    return t + i;
}
char *cpy_1(char *t, const char *s)
{
    for ( ; *s; ++s, ++t)
        *t = *s;
    *t = *s;
    ++t;
    return t;
}
char *cpy_2(char *t, const char *s)
{
    while (*t++ = *s++)
        ;
    return t;
}
like image 38
CapelliC Avatar answered Sep 21 '22 03:09

CapelliC