2007年4月30日 星期一

範例: 如何使用指標指向指標陣列(Pointer Array)

array4.c

#include
#include
#include

struct abc {
int val;
char str[10];
};

void allocatemem(void*** a1) {
int amount;

printf("s1 - &a1: %10p, a1: %10p, *a1: %10p\n", a1, *a1, **a1);
amount = sizeof(struct abc)*16;
if ((*a1=(void**)malloc(amount))==NULL) {
printf("errno: %s, desc: %s\n", errno, strerror(errno));
}
printf("s2 - &a1: %10p, a1: %10p, *a1: %10p\n", a1, *a1, **a1);

memset(*a1, 0, amount);
//printf("memset ok\n");
printf("s4 - &a1: %10p, a1: %10p, *a1: %10p\n", a1, *a1, **a1);

}

int main(int argc, char** argv) {
struct abc *(*a1)[16];
printf("s0 - &a1: %10p, a1: %10p, &a1[0]: %10p, a1[0]: %10p, *a1: %10p , **a1: %10p, a1[1]: %10p\n", &a1, a1, &a1[0], a1[0], *a1, **a1, a1[1]);
allocatemem((void***)&a1);
printf("s5 - &a1: %10p, a1: %10p, &a1[0]: %10p, a1[0]: %10p, *a1: %10p , **a1: %10p, a1[1]: %10p\n", &a1, a1, &a1[0], a1[0], *a1, **a1, a1[1]);

return 0;
}

# gcc -g -o a4 ./array4.c

執行結果
# ./a4
s0 - &a1: 0xfeeac584, a1: 0x943c80, &a1[0]: 0x943c80, a1[0]: 0x943c80, *a1: 0x943c80 , **a1: (nil), a1[1]: 0x943cc0
s1 - &a1: 0xfeeac584, a1: 0x943c80, *a1: (nil)
s2 - &a1: 0xfeeac584, a1: 0x8aa5008, *a1: (nil)
s4 - &a1: 0xfeeac584, a1: 0x8aa5008, *a1: (nil)
s5 - &a1: 0xfeeac584, a1: 0x8aa5008, &a1[0]: 0x8aa5008, a1[0]: 0x8aa5008, *a1: 0x8aa5008 , **a1: (nil), a1[1]: 0x8aa5048

沒有留言: