## C 指针的算术运算

C 指针

C 指针是一个用数值表示的地址。因此，您可以对指针执行算术运算。可以对指针进行四种算术运算：++、--、+、-。

```ptr++
```

## 递增一个指针

```#include <stdio.h>

const int MAX = 3;

int main ()
{
int  var[] = {10, 100, 200};
int  i, *ptr;

/* 指针中的数组地址 */
ptr = var;
for ( i = 0; i < MAX; i++)
{

printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );

/* 移动到下一个位置 */
ptr++;
}
return 0;
}
```

```Address of var[0] = bf882b30
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
```

## 递减一个指针

```#include <stdio.h>

const int MAX = 3;

int main ()
{
int  var[] = {10, 100, 200};
int  i, *ptr;

/* 指针中最后一个元素的地址 */
ptr = &var[MAX-1];
for ( i = MAX; i > 0; i--)
{

printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );

/* 移动到下一个位置 */
ptr--;
}
return 0;
}
```

```Address of var[3] = bfedbcd8
Value of var[3] = 200
Value of var[2] = 100
Value of var[1] = 10
```

## 指针的比较

```#include <stdio.h>

const int MAX = 3;

int main ()
{
int  var[] = {10, 100, 200};
int  i, *ptr;

/* 指针中第一个元素的地址 */
ptr = var;
i = 0;
while ( ptr <= &var[MAX - 1] )
{

printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );

/* 指向上一个位置 */
ptr++;
i++;
}
return 0;
}
```

```Address of var[0] = bfdbcb20
Value of var[0] = 10