位置:首頁 > 高級語言 > Objective-C教學 > Objective-C 數組的指針

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