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\n", 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];

这将ptr声明为 MAX 整数指针数组。因此,ptr 中的每个元素现在都保存一个指向 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\n", 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\n", 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
Objective_c_pointers.htm