reference
i++先赋值再运算;++i先运算再赋值
q=*p++; //等价于 q=*p; p++;
q=*(p++); //等价于 q=*p; p++;
*和++的优先级是相同的,运算符的结合都是自右向左的,因此 ++只对 p 产生作用,而不是*p
https://blog.csdn.net/jingjingaibiancheng/article/details/88653026
https://blog.csdn.net/nanfeibuyi/article/details/80834983
example 1
#include <iostream>
using namespace std;
int main() {
char blocks[3] = {'A', 'F', 'X'};
char *ptr = blocks;
cout << *++ptr << endl;
cout << ++*ptr << endl; // address do not change; only the content change 取了值之后,已经和指针没有关系了
cout << (*ptr)++ << endl; // address do not change; only the content change 取了值之后,已经和指针没有关系了
cout << *ptr << endl;
for (int i = 0; i < 3; i++)
cout << "Final blocks[i] is: " << blocks[i] << endl;
return 0;
}
// F
// G
// G
// H
// Final blocks[i] is: A
// Final blocks[i] is: H
// Final blocks[i] is: X
example 2
#include <iostream>
using namespace std;
int main() {
char blocks[3] = {'A', 'F', 'X'};
char *ptr = blocks;
cout << *++ptr << endl; // F
cout << ++*ptr << endl; // G 取了值之后,已经和指针没有关系了
cout << *ptr++ << endl; // G ptr先赋值 然后ptr再加1(所以地址加1)
cout << *ptr << endl;
for (int i = 0; i < 3; i++)
cout << "Final blocks[i] is: " << blocks[i] << endl;
return 0;
}
F
G
G
X
Final blocks[i] is: A
Final blocks[i] is: G
Final blocks[i] is: X
example 3
#include<iostream>
using namespace std;
int main() {
int a[4] = {1,3,9};
int *p=a;
// cout << "*p:" << *p << endl; // 1
// cout << "*p++:" << *p++ << endl; // 1 p先赋值 然后p再加1(所以地址加1)
// cout << "*p++:" << *p << endl; // 3
cout << "*p:" << *p << endl; // 1
cout << "*p++:" << (*p)++ << endl; // 1 还是先赋值 再加1 但是此处取了值之后,已经和指针没有关系了
cout << "*p++:" << *p << endl; // 2
// cout << "*p:" << *p << endl; // 1
// cout << "*p++:" << *++p << endl; // 3 地址先加1 再赋值
// cout << "*p++:" << *p << endl; // 3
return 0;
}