Misunderstanding c ++ and - pointer arithmetic

So, I learn about pointers using http://cplusplus.com/doc/tutorial/pointers/ , and I don’t understand anything about the pointer arithmetic section. Can someone clarify the situation or point me to a textbook about this that I can better understand.

I was especially confused with all the staples such things as the difference between the *p++, (*p)++, *(p++)etc.

+5
source share
4 answers

*p++

++ , *, , , post-increment , .

(*p)++

, , ( ).

*(p++)

, , .

, , , . :

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

char - , ++ 1 ( ).

short , ++ 2, , .

long - , ++ 4.

+4

strcpy, Kernighan/Ritchie ( , , , ): cpy_0, cpy_1, cpy_2 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;
}
+1
*p++

, * p, (postincrement). :

int numbers[2];
int *p;
p = &numbers[0];
*p = 4;        //numbers[0] = 4;
*(p + 1) = 8;  //numbers[1] = 8;
int a = *p++;  //a = 4 (the increment takes place after the evaluation)
               //*++p would have returned 8 (a = 8)
int b = *p;    //b = 8 (p is now pointing to the next integer, not the initial one)

:

(*p)++

, * p = * p + 1;.

(p++); //same as p++

, ( ) , .

0
source

You must first understand what post increment does.
The increment post increases the variable by one BUT , the expression (p ++) returns the original value of the variable that will be used in the rest of the expression.

char   data[] = "AX12";
char* p;

p = data;
char* a = p++;

// a -> 'A'  (the original value of p was returned from p++ and assigned to a)
// p -> 'X'

p = data;   // reset;
char  l =  *(p++);

// l =  'A'. The (p++) increments the value of p. But returns the original
             value to be used in the remaining expression. Thus it is the
             original value that gets de-referenced by * so makeing l 'A'
// p -> 'X'

Now due to operator precedence:

*p++ is equivalent to *(p++)

Finally, we have a complex:

p = data;
char m = (*p)++;

// m is 'A'. First we deference 'p' which gives us a reference to 'A'
//           Then we apply the post increment which applies to the value 'A' and makes it a 'B'
//           But we return the original value ('A') to be used in assignment to 'm'

// Note 1:   The increment was done on the original array
//           data[]  is now "BXYZ";
// Note 2:   Because it was the value that was post incremented p is unchaged.
// p -> 'B' (Not 'X')
0
source

All Articles