Objective-C 数组的指针
在我们了解指针数组的概念,让我们考虑下面的例子,这使得使用3个整数的数组:
#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; }
上面的代码编译和执行时,它会产生以下结果:
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
可能有情况时,我们要保持一个数组,它可以存储指针int或char或任何其他数据类型可用。以下是一个整数指针数组的声明:
int *ptr[MAX];
此声明指针数组的最大整数指针。因此,每一个元素的指针,现在持有一个int值的指针。下面的示例使用三个整数,将被存储在一个数组中的指针如下:
#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; }
上面的代码编译和执行时,它会产生以下结果:
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
也可以使用一个指针数组,字符存储的字符串列表如下:
#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; }
上面的代码编译和执行时,它会产生以下结果:
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