【发布时间】:2014-06-20 11:59:32
【问题描述】:
我定义了一个数据结构 (Foo),其中包含指向自身的 25 个指针 (members) 的数组。我想将这些指针中的每一个初始化为NULL,但我的 init 函数无法正常工作。当我的Foo f 从foo_init() 返回时,members 中只有一部分是NULL,其他只是填充了随机值。
//in Foo.h
#include <stdio.h>
#include <stdlib.h>
typedef struct Foo {
struct Foo * members[25] ;
} Foo ;
void foo_init(Foo * f) ;
//in Foo.c
void foo_init(Foo * f) {
f = (Foo*)malloc(sizeof(Foo));
for (size_t i = 0 ; i < 25 ; i++) {
f->members[i] = NULL ;
}
/* Ok here, all members are NULL */
}
//in main.c
#include "Foo.h"
int main(int argc, const char * argv[])
{
Foo f ;
foo_init(&f) ;
/* why isn't every index of f.members NULL? */
/* ... */
return 0;
}
我通过 LLDB 运行我的代码。在 foo_init() 内部,所有的 members 都是 NULL。但是从 foo_init() 返回后,f.members 充满了随机垃圾值。
【问题讨论】:
-
你的编译器不抱怨你的代码吗?
-
@ThomasPadron-McCarthy:我想应该...
-
这是一个错字,对不起。修好了。
-
为什么
malloc进入你的类对象? -
您正在为
foo_init的第一行中已在堆栈上声明的内容分配堆内存。摆脱那条线。
标签: c arrays pointers initialization