malloc() 调用不会跨函数持续存在
malloc() call does not persist across functions
代码:
struct Adjacent {
char* c;
int done_at;
};
typedef struct Adjacent Adj;
struct Container {
Adj* m;
};
typedef struct Container Cont;
void alloc_stuff(Cont *cont) {
cont = (Cont*)malloc(100 * sizeof(Cont));
memset(cont, 0, 100 * sizeof(Cont));
for (int i = 0; i < 100; ++i) {
cont[i].m = (Adj*)malloc(50 * sizeof(Adj));
memset(cont[i].m, 0, 50 * sizeof(Adj));
cont[i].m->c = (char*)malloc(50 * sizeof(char));
memset(cont[i].m->c, 0, 50 * sizeof(char));
cont[i].m->done_at = 0;
}
}
int main() {
Cont* cont = NULL;
alloc_stuff(cont);
// cont still NULL here
}
为什么 cont
在 alloc_stuff()
之后是 NULL?
是因为这一行:
void alloc_stuff(Cont *cont)
变量 cont 是传递给函数的原始指针的副本。
如果你想修改原来的指针,你应该使用这样的东西:
void alloc_stuff(Cont **cont)
alloc_stuff(cont);
将 cont
的值传递给 alloc_stuff
.
alloc_stuff
没有收到任何对 cont
的引用。 alloc_stuff
内的任何更改都不会影响 cont
。
要在 main
中更改 cont
的值,您应该将 alloc_stuff
修改为 return 一个指针并使用 cont = alloc_stuff();
,或者您应该修改 alloc_stuff
以接受指向 Cont *
的指针(因此它将是 Cont **
),然后修改其中的代码以使用 *cont
当前使用 [=11] =],之后你可以用alloc_stuff(&cont);
调用它。 (或者,在需要括号的地方,使用 (*cont)
代替 cont
。)
代码:
struct Adjacent {
char* c;
int done_at;
};
typedef struct Adjacent Adj;
struct Container {
Adj* m;
};
typedef struct Container Cont;
void alloc_stuff(Cont *cont) {
cont = (Cont*)malloc(100 * sizeof(Cont));
memset(cont, 0, 100 * sizeof(Cont));
for (int i = 0; i < 100; ++i) {
cont[i].m = (Adj*)malloc(50 * sizeof(Adj));
memset(cont[i].m, 0, 50 * sizeof(Adj));
cont[i].m->c = (char*)malloc(50 * sizeof(char));
memset(cont[i].m->c, 0, 50 * sizeof(char));
cont[i].m->done_at = 0;
}
}
int main() {
Cont* cont = NULL;
alloc_stuff(cont);
// cont still NULL here
}
为什么 cont
在 alloc_stuff()
之后是 NULL?
是因为这一行:
void alloc_stuff(Cont *cont)
变量 cont 是传递给函数的原始指针的副本。
如果你想修改原来的指针,你应该使用这样的东西:
void alloc_stuff(Cont **cont)
alloc_stuff(cont);
将 cont
的值传递给 alloc_stuff
.
alloc_stuff
没有收到任何对 cont
的引用。 alloc_stuff
内的任何更改都不会影响 cont
。
要在 main
中更改 cont
的值,您应该将 alloc_stuff
修改为 return 一个指针并使用 cont = alloc_stuff();
,或者您应该修改 alloc_stuff
以接受指向 Cont *
的指针(因此它将是 Cont **
),然后修改其中的代码以使用 *cont
当前使用 [=11] =],之后你可以用alloc_stuff(&cont);
调用它。 (或者,在需要括号的地方,使用 (*cont)
代替 cont
。)