不理解带有++和--的指针算术
Not Understanding Pointer Arithmetic with ++ and --
因此,我通过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++
增加指针,使其指向声明指针时定义的大小的下一个元素(可能不存在(。
相关文章:
- 为什么指针不写入类的地址?
- 不理解为什么代码没有产生所需的答案
- 为什么"具有常量成员的结构"类型的指针不能指向"具有非常量成员的结构"?
- 当目标指针不是基类的类型时,为什么允许dynamic_cast为多态类生成 null 指针?
- C++我不理解的行为
- 比较两个 constexpr 指针不是 constexpr?
- 为什么智能指针不能用通常的指针方式声明
- 字符指针不递增?
- C++为什么原始指针不会增加shared_ptr的引用计数?
- Visual Studio代码不理解CMake-DDEBUG
- 为什么在C++中使用delete后指针不为NULL
- 堆指针不会被分配给数组有什么原因吗
- 指向类中函数方法的指针不起作用
- 不理解此递归函数中的返回 (C++)
- 在 c++ 中返回矢量的指针不起作用
- 不理解将 .pb 转换为 ff-lite 时的平均值和标准开发值
- 不理解带有++和--的指针算术
- 不理解指针增量答案
- 不理解如何初始化源/接收类逻辑的指针
- 不理解在这个例子中指针和类是如何协同工作的