指针默认值。? [英] pointer default value .?
问题描述
看,
typedef struct jig
{
int *a;
int *b;
}temp;
现在阶段1
temp *b;
b= (temp*)malloc(sizeof(temp));
if(b->a != NULL)
printf("a is not null\n");
else
printf("a is null\n");
if(b->b != NULL)
printf("b is not null\n");
else
printf("b is null\n");
输出是:
a is null
b is null
现在阶段2
temp b;
if(b.a != NULL)
printf("a is not null\n");
else
printf("a is null\n");
if(b.b != NULL)
printf("b is not null\n");
else
printf("b is null\n");
输出是:
a is not null
b is not null
为什么发生这种情况?
why this is happening?
推荐答案
指针没有默认值。它们的价值就是无论垃圾是他们现在正在使用的内存。有时,一个特定的编译器将清零内存,但是这不是标准的,所以不要指望它。)
Pointers have no default value. The value they have is just whatever junk was in the memory they're using now. Sometimes a specific compiler will zero out memory, but that's not standard so don't count on it.)
这是的malloc空的记忆是一个巧合;它可能很容易被任何其他值。你需要和应始终手动所有指针设置为NULL。
The memory from malloc being NULL was a coincidence; it could have been any other value just as easily. You need to and should always manually set all your pointers to NULL.
另一种方法是,你还可以使用释放calloc,它做同样的事情,但malloc的所有设置位0在记忆它给你块。这不会堆栈变量帮助的,所以你还是自己设置这些为NULL。
Another alternative is you can also use calloc, which does the same thing as malloc but sets all bits to 0 in the block of memory it gives you. This doesn't help with stack variables though, so you still have to set those to NULL by yourself.
这篇关于指针默认值。?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!