# Objective-C 指針運算

Objective-C 的指針是一個地址，它是一個數值。因此可以在數值上的指針執行算術運算。有四種，可以用來對指針的算術運算符：+ +， - ，+， -

ptr++

## 遞增一個指針

#import <Foundation/Foundation.h> const int MAX = 3; int main () { int var[] = {10, 100, 200}; int i, *ptr; /* let us have array address in yiibaier */ ptr = var; for ( i = 0; i < MAX; i++) { NSLog(@"Address of var[%d] = %x
", i, ptr ); NSLog(@"Value of var[%d] = %d
", i, *ptr ); /* move to the next location */ ptr++; } return 0; }

2013-09-14 00:08:36.215 demo[32000] Address of var[0] = 7e6f2a70
2013-09-14 00:08:36.216 demo[32000] Value of var[0] = 10
2013-09-14 00:08:36.216 demo[32000] Address of var[1] = 7e6f2a74
2013-09-14 00:08:36.216 demo[32000] Value of var[1] = 100
2013-09-14 00:08:36.216 demo[32000] Address of var[2] = 7e6f2a78
2013-09-14 00:08:36.216 demo[32000] Value of var[2] = 200

## 遞減指針

#import <Foundation/Foundation.h> const int MAX = 3; int main () { int var[] = {10, 100, 200}; int i, *ptr; /* let us have array address in yiibaier */ ptr = &var[MAX-1]; for ( i = MAX; i > 0; i--) { NSLog(@"Address of var[%d] = %x
", i, ptr ); NSLog(@"Value of var[%d] = %d
", i, *ptr ); /* move to the previous location */ ptr--; } return 0; }

2013-09-14 00:12:22.783 demo[13055] Address of var[3] = ea4c618
2013-09-14 00:12:22.783 demo[13055] Value of var[3] = 200
2013-09-14 00:12:22.783 demo[13055] Address of var[2] = ea4c614
2013-09-14 00:12:22.783 demo[13055] Value of var[2] = 100
2013-09-14 00:12:22.783 demo[13055] Address of var[1] = ea4c610
2013-09-14 00:12:22.783 demo[13055] Value of var[1] = 10

## 指針比較

#import <Foundation/Foundation.h> const int MAX = 3; int main () { int var[] = {10, 100, 200}; int i, *ptr; /* let us have address of the first element in yiibaier */ ptr = var; i = 0; while ( ptr <= &var[MAX - 1] ) { NSLog(@"Address of var[%d] = %x
", i, ptr ); NSLog(@"Value of var[%d] = %d
", i, *ptr ); /* yiibai to the previous location */ ptr++; i++; } return 0; }

2013-09-14 00:15:49.976 demo[24825] Address of var[0] = ae1235a0 2013-09-14 00:15:49.976 demo[24825] Value of var[0] = 10 2013-09-14 00:15:49.977 demo[24825] Address of var[1] = ae1235a4 2013-09-14 00:15:49.977 demo[24825] Value of var[1] = 100 2013-09-14 00:15:49.977 demo[24825] Address of var[2] = ae1235a8 2013-09-14 00:15:49.977 demo[24825] Value of var[2] = 200