前文谈到local指针数组声明为:int *ptrAry[LEN](以int为例)。那么global的指针数组如何声明和分配内存呢?

完整例子如下:

#define ARYLEN  10

int main(int argc, char const *argv[])
{
  int ary[ARYLEN];
  // an dynamic array of pointer
  int **dynPtrAry = calloc(ARYLEN, sizeof(int *) ); 
  int i;

  for(i = 0; i < ARYLEN; i++) { // a regular array
    ary[i] = i;
  }

  for(i = 0; i < ARYLEN; i++) { 
    dynPtrAry[i] = &ary[i];
  }

  for(i = 0; i < ARYLEN; i++) {
    printf("ary[%d]:%d ptr:%p - dynPtrAry[%d]:%p deref:%d\n", 
      i, ary[i], &ary[i], i, dynPtrAry[i], *dynPtrAry[i]);
  }

  free(dynPtrAry);
  return 0;
}

运行结果:

==3698== Memcheck, a memory error detector
==3698== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==3698== Using Valgrind-3.12.0.SVN and LibVEX; rerun with -h for copyright info
==3698== Command: ./dynPtrAry
==3698== 
ary[0]:0 ptr:0xffefffbd0 - dynPtrAry[0]:0xffefffbd0 deref:0
ary[1]:1 ptr:0xffefffbd4 - dynPtrAry[1]:0xffefffbd4 deref:1
ary[2]:2 ptr:0xffefffbd8 - dynPtrAry[2]:0xffefffbd8 deref:2
ary[3]:3 ptr:0xffefffbdc - dynPtrAry[3]:0xffefffbdc deref:3
ary[4]:4 ptr:0xffefffbe0 - dynPtrAry[4]:0xffefffbe0 deref:4
ary[5]:5 ptr:0xffefffbe4 - dynPtrAry[5]:0xffefffbe4 deref:5
ary[6]:6 ptr:0xffefffbe8 - dynPtrAry[6]:0xffefffbe8 deref:6
ary[7]:7 ptr:0xffefffbec - dynPtrAry[7]:0xffefffbec deref:7
ary[8]:8 ptr:0xffefffbf0 - dynPtrAry[8]:0xffefffbf0 deref:8
ary[9]:9 ptr:0xffefffbf4 - dynPtrAry[9]:0xffefffbf4 deref:9
==3698== 
==3698== HEAP SUMMARY:
==3698==     in use at exit: 0 bytes in 0 blocks
==3698==   total heap usage: 2 allocs, 2 frees, 1,104 bytes allocated
==3698== 
==3698== All heap blocks were freed -- no leaks are possible
==3698== 
==3698== For counts of detected and suppressed errors, rerun with: -v
==3698== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

没有内存泄漏。