未初始化的指针称为野生指针, 因为它们指向某个任意的内存位置, 并且可能导致程序崩溃或行为不佳。
int main()
{
int *p; /* wild pointer */
/* Some unknown memory location is being corrupted.
This should never be done. */
*p = 12;
}
请注意, 如果指针p指向已知变量, 则它不是通配指针。在下面的程序中, p一直指向该指针, 直到指向a为止。
int main()
{
int *p; /* wild pointer */
int a = 10;
p = &a; /* p is not a wild pointer now*/
*p = 12; /* This is fine. Value of a is changed */
}
如果我们想要一个指向一个值(或一组值)的指针而没有该值的变量, 则应该显式分配内存并将该值放入分配的内存中。
int main()
{
int *p = ( int *) malloc ( sizeof ( int ));
*p = 12; /* This is fine (assuming malloc doesn't return NULL) */
}
评论前必须登录!
注册