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;
    }
    
    编译并执行上述代码后,将产生以下结果-
    
    2020-08-08 09:36:45.574 test[5172:9900] Value of var[0] = 10
    2020-08-08 09:36:45.581 test[5172:9900] Value of var[1] = 100
    2020-08-08 09:36:45.581 test[5172:9900] 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;
    }
    
    
    2020-08-08 09:43:11.193 test[6272:5204] Value of var[0] = 10
    2020-08-08 09:43:11.200 test[6272:5204] Value of var[1] = 100
    2020-08-08 09:43:11.200 test[6272:5204] 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;
    }
    
    
    2020-08-08 09:46:37.647 test[5568:884] Value of names[0] = Zara Ali
    2020-08-08 09:46:37.654 test[5568:884] Value of names[1] = Hina Ali
    2020-08-08 09:46:37.654 test[5568:884] Value of names[2] = Nuha Ali
    2020-08-08 09:46:37.654 test[5568:884] Value of names[3] = Sara Ali