C pointer to pointer

Object **self 是 C 語言的 pointer to pointer,常用在想在 callee 操作 caller 的資料。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
struct Object {
int a, b;
}

typedef struct Object Obejct;

int init_object(Object **self) { // call-by-value
if (NULL == (*self = malloc(sizeof(Object))))
return -1;
(*self)->a = 0;
(*self)->b = 0;
return 0;
}

int main(int argc, char *argv[]) {
Object *o = NULL;
init_object(&o);
o->a = 9922;
o->b = 5566;
return 0;
}

C Pointer to pointer

C 語言是 call by value, self 的 value 是 &o 的 value,也就是 o 的 address。在 init_object()self dereference、用 *self 操作等同用 o 操作,所以 *self = malloc(sizeof(Object)) 等同讓 o 指向新 allocate 出來的 memory,而 (*self)->a 等同 o->ao 是個 Object 的 pointer, o->a 是它指向的 Object 的 field a(*self)->a = 0 是在初始化 main()o pointer 指向的 Object

如果不使用 pointer to pointer,像下面這樣會發生什麼事?

1
2
3
4
5
6
7
8
9
10
11
int init_object(Object *self) {
if (NULL == (self = malloc(sizeof(Object))))
return -1;
self->a = 0;
self->b = 0;
}

int main(int argc, char *argv[]) {
Object *o = NULL;
init_object(o);
}

這時候 self 的 value 是 o 的 value,也就是 NULL。在 init_object()self 是個 local variable,allocate 一塊 Object 大小的 memory 給它以及其他操作都不會如我們希望的影響到 main() 裡的 o