2007年5月1日 星期二

如何傳遞陣列指標(function variable) 在函數中

#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);
}


void filldata(struct abc (*aa)[16]) {
printf("s6 - &aa: %10p, aa: %10p, *aa: %10p, &(*aa)[0]: %10p, &(*aa)[1]: %10p\n", &aa, aa, *aa, &(*aa)[0], &(*aa)[1]);
(*aa)[0].val = 0;
strcpy((*aa)[0].str, "hello0");
printf("aa[0] ok\n");

(*aa[1]).val = 1;
strcpy((*aa[1]).str, "hello1");
printf("aa[1] ok\n");
}

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

return 0;
}

# gcc -o a5 ./array5.c

# ./a5
s0 - &a1: 0xfeee4444, a1: 0x943c80, *a1: 0x943c80, &(*a1)[0]: 0x943c80, &(*a1)[1]: 0x943c90
s1 - &a1: 0xfeee4444, a1: 0x943c80, *a1: (nil)
s2 - &a1: 0xfeee4444, a1: 0x8820008, *a1: (nil)
s4 - &a1: 0xfeee4444, a1: 0x8820008, *a1: (nil)
s5 - &a1: 0xfeee4444, a1: 0x8820008, *a1: 0x8820008, &(*a1)[0]: 0x8820008, &(*a1)[1]: 0x8820018
s6 - &aa: 0xfeee4420, aa: 0x8820008, *aa: 0x8820008, &(*aa)[0]: 0x8820008, &(*aa)[1]: 0x8820018
aa[0] ok
aa[1] ok

沒有留言: