null
悬空指针
指向已被删除(或释放)的内存位置的指针称为悬挂指针。有 三 指针作为悬挂指针的不同方式
- 取消内存分配
// Deallocating a memory pointed by ptr causes
// dangling pointer
#include <stdlib.h>
#include <stdio.h>
int
main()
{
int
*ptr = (
int
*)
malloc
(
sizeof
(
int
));
// After below free call, ptr becomes a
// dangling pointer
free
(ptr);
// No more a dangling pointer
ptr = NULL;
}
- 函数调用
// The pointer pointing to local variable becomes
// dangling when local variable is not static.
#include<stdio.h>
int
*fun()
{
// x is local variable and goes out of
// scope after an execution of fun() is
// over.
int
x = 5;
return
&x;
}
// Driver Code
int
main()
{
int
*p = fun();
fflush
(stdin);
// p points to something which is not
// valid anymore
printf
(
"%d"
, *p);
return
0;
}
输出:
A garbage Address
如果x是一个静态变量,则不会出现上述问题(或者p不会悬空)。
// The pointer pointing to local variable doesn't
// become dangling when local variable is static.
#include<stdio.h>
int
*fun()
{
// x now has scope throughout the program
static
int
x = 5;
return
&x;
}
int
main()
{
int
*p = fun();
fflush
(stdin);
// Not a dangling pointer as it points
// to static variable.
printf
(
"%d"
,*p);
}
输出:
5
- 变量超出范围
void main() { int *ptr; ..... ..... { int ch; ptr = &ch; } ..... // Here ptr is dangling pointer }
Void pointer是一种特定的指针类型–Void*–指向存储器中某个数据位置的指针,它没有任何特定类型。Void指的是类型。基本上,它指向的数据类型可以是任何类型。如果我们将char数据类型的地址分配给void pointer,它将成为char pointer,如果是int数据类型,则是int pointer,依此类推。任何指针类型都可以转换为空指针,因此它可以指向任何值。 要点
- 空指针 无法取消引用 。不过,可以使用空指针进行类型转换
- 由于缺乏具体的值和大小,指针算法不可能在void指针上实现。
例子:
#include<stdlib.h> int main() { int x = 4; float y = 5.5; //A void pointer void *ptr; ptr = &x; // (int*)ptr - does type casting of void // *((int*)ptr) dereferences the typecasted // void pointer variable. printf ( "Integer variable is = %d" , *( ( int *) ptr) ); // void pointer is now float ptr = &y; printf ( "Float variable is= %f" , *( ( float *) ptr) ); return 0; } |
输出:
Integer variable is = 4 Float variable is= 5.500000
参考 无效指针文章 详细信息。
空指针是指不指向任何内容的指针。在这种情况下,如果我们没有地址分配给指针,那么我们可以简单地使用NULL。
#include <stdio.h> int main() { // Null Pointer int *ptr = NULL; printf ( "The value of ptr is %p" , ptr); return 0; } |
输出:
The value of ptr is (nil)
要点
- 空指针与未初始化指针- 未初始化的指针存储未定义的值。空指针存储定义的值,但环境定义的值不是任何成员或对象的有效地址。
- 空指针与空指针 –Null pointer是一个值,而void pointer是一个类型
尚未初始化为任何值(甚至不为NULL)的指针称为“野生指针”。指针可能被初始化为非空垃圾值,该值可能不是有效地址。
int main() { int *p; /* wild pointer */ int x = 10; // p is not a wild pointer now p = &x; return 0; } |
本文由 斯普尔蒂·阿伦 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END