1
struct findaddress {
     struct findaddress *next[11];
     struct user *myuser;
};
int main(void){
struct findaddress *findhead=(struct findaddress *)(malloc(sizeof(struct findaddress)));
    int i=0;
    for (i;i!=11;i++){
        if (findhead->next[i]==NULL)puts("success");else puts("fail");
    }
    return 0;
}

结果,对我来说足够令人不安的是:

fail
fail
success
success
success
success
success
success
success
success
success

知道为什么底部的两个指针失败,而其他指针正在传递。

有没有好心人来开导我?

4

2 回答 2

5

malloc()不初始化内存,只分配堆上的空间。您看到的数组内容是随机的。它只是同一区域的先前内容。

如果calloc()您想确保它用零初始化,请使用。

于 2013-06-17T03:52:18.387 回答
2

Why did you expect anything to be initialized to anything in this case? malloc does not initialize the allocated memory at all, which is basically what you are observing in your experiment.

If you want to zero-initialize your struct object, do

*findhead = (struct findaddress) { 0 };

after malloc. Or, if you want your memory to be filled with physical all-bits-zero pattern, use calloc instead of malloc.

P.S. What is the purpose of that i in the first part of for (i;i!=11;i++)? If your i is already pre-initialized, you can just do for (;i!=11;i++).

于 2013-06-17T04:00:43.963 回答