在我們了解指針數(shù)組的概念,讓我們考慮下面的例子,這使得使用3個(gè)整數(shù)的數(shù)組:
#import <Foundation/Foundation.h> const int MAX = 3; int main () { int var[] = {10, 100, 200}; int i; for (i = 0; i < MAX; i++) { NSLog(@"Value of var[%d] = %d ", i, var[i] ); } return 0; }
上面的代碼編譯和執(zhí)行時(shí),它會產(chǎn)生以下結(jié)果:
2013-09-14 00:22:57.136 demo[18206] Value of var[0] = 10 2013-09-14 00:22:57.136 demo[18206] Value of var[1] = 100 2013-09-14 00:22:57.136 demo[18206] Value of var[2] = 200
可能有情況時(shí),我們要保持一個(gè)數(shù)組,它可以存儲指針int或char或任何其他數(shù)據(jù)類型可用。以下是一個(gè)整數(shù)指針數(shù)組的聲明:
int *ptr[MAX];
此聲明指針數(shù)組的最大整數(shù)指針。因此,每一個(gè)元素的指針,現(xiàn)在持有一個(gè)int值的指針。下面的示例使用三個(gè)整數(shù),將被存儲在一個(gè)數(shù)組中的指針如下:
#import <Foundation/Foundation.h> const int MAX = 3; int main () { int var[] = {10, 100, 200}; int i, *ptr[MAX]; for ( i = 0; i < MAX; i++) { ptr[i] = &var[i]; /* assign the address of integer. */ } for ( i = 0; i < MAX; i++) { NSLog(@"Value of var[%d] = %d ", i, *ptr[i] ); } return 0; }
上面的代碼編譯和執(zhí)行時(shí),它會產(chǎn)生以下結(jié)果:
2013-09-14 00:27:47.904 demo[3825] Value of var[0] = 10 2013-09-14 00:27:47.905 demo[3825] Value of var[1] = 100 2013-09-14 00:27:47.905 demo[3825] Value of var[2] = 200
也可以使用一個(gè)指針數(shù)組,字符存儲的字符串列表如下:
#import <Foundation/Foundation.h> const int MAX = 4; int main () { char *names[] = { "Zara Ali", "Hina Ali", "Nuha Ali", "Sara Ali", }; int i = 0; for ( i = 0; i < MAX; i++) { NSLog(@"Value of names[%d] = %s ", i, names[i] ); } return 0; }
上面的代碼編譯和執(zhí)行時(shí),它會產(chǎn)生以下結(jié)果:
2013-09-14 00:30:25.438 demo[13476] Value of names[0] = Zara Ali 2013-09-14 00:30:25.439 demo[13476] Value of names[1] = Hina Ali 2013-09-14 00:30:25.439 demo[13476] Value of names[2] = Nuha Ali 2013-09-14 00:30:25.439 demo[13476] Value of names[3] = Sara Ali