指针是一个用数值表示的地址。因此,您可以对指针执行算术运算。可以对指针进行四种算术运算:++、–、+、-。
假设 ptr 是一个指向地址 1000 的整型指针,是一个 4个字节的整数,让我们对该指针执行下列的算术运算:
ptr++
例一:
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include <iostream> using namespace std; int main () { int *ptr; int a=3; ptr=&a; cout << "ptr value is " << ptr<<endl ; cout<<++ptr; return 0; } |
例二:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include <iostream> using namespace std; const int n = 3; int main () { int array[n] = {10, 100, 200}; int *ptr; cout<<"address of array: "; cout<<array<<endl; ptr = array; for (int i = 0; i < n; i++){ cout << "Address of var[" << i << "] = "; cout << ptr << endl; cout << "Value of var[" << i << "] = "; cout << *ptr << endl; ptr++; } return 0; } |
递减一个指针
同样地,对指针进行递减运算,即把值减去其数据类型的字节数,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include <iostream> using namespace std; const int n = 3; int main () { int array[n] = {10, 100, 200}; int *ptr; cout<<"address of array: "; cout<<array<<endl; ptr = &array[n-1]; for (int i = n; i > 0; i--) { cout << "Address of var[" << i << "] = "; cout << ptr << endl; cout << "Value of var[" << i << "] = "; cout << *ptr << endl; ptr--; } return 0; } |