不理解带有++和--的指针算术

Not Understanding Pointer Arithmetic with ++ and --

本文关键字:指针 不理解      更新时间:2023-10-16

因此,我通过http://cplusplus.com/doc/tutorial/pointers/并且我对指针算术部分一无所知。有人能澄清一下吗?或者给我指一个我可能更理解的教程。

我特别困惑于所有的括号,比如*p++(*p)++*(p++)等之间的差异。

*p++

对于这一个,++的优先级高于*,因此它将指针递增一,但在原始位置检索值,因为递增后返回指针,然后递增其值。

(*p)++

这会迫使优先级朝另一个方向,因此指针首先被取消引用,然后该位置的值增加一(但返回原始指针位置的值(。

*(p++)

这个先增加指针,这样它的作用与第一个指针相同。

需要注意的一点是,指针的增量受指针类型的影响。从您提供的链接:

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

char的长度是一个字节,因此++将指针增加1(因为指针指向每个字节的开头(。

CCD_ 11的长度是两个字节,因此CCD_。

CCD_ 13的长度是四个字节,因此CCD_。

几年前,我发现Kernighan/Ritchie对strcpy的解释很有用(我现在没有文本,希望代码准确(: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;
}

首先,您必须了解后增量的作用
增量后,将变量增加一BUT表达式(p++(返回要在表达式的其余部分中使用的变量的原始值。

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'

现在因为操作员优先:

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

最后我们有一个复杂的:

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')
*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++

增加指针,使其指向声明指针时定义的大小的下一个元素(可能不存在(。