代码之家  ›  专栏  ›  技术社区  ›  Ash

“取消引用空指针”究竟是什么意思?

  •  44
  • Ash  · 技术社区  · 14 年前

    我是一个C的新手,在我的大学工作中,我在代码中遇到了一些注释,这些注释经常引用一个空指针。我确实有过C的背景,我一直认为这可能类似于你在.NET中得到的“nullreferenceexception”,但现在我有严重的疑问。

    有人能用外行的话跟我解释一下这到底是什么,为什么是坏的吗?

    5 回复  |  直到 10 年前
        1
  •  63
  •   Greg Hewgill    14 年前

    NULL 0x00000000 *

    int a, b, c; // some integers
    int *pi;     // a pointer to an integer
    
    a = 5;
    pi = &a; // pi points to a
    b = *pi; // b is now 5
    pi = NULL;
    c = *pi; // this is a NULL pointer dereference
    

    NullReferenceException

        2
  •  27
  •   Adam Rosenfield    14 年前

    * x *x & &x & y

    *(&x) == x
    &(*y) == y
    

    int *x = NULL;  // x is a null pointer
    int y = *x;     // CRASH: dereference x, trying to read it
    *x = 0;         // CRASH: dereference x, trying to write it
    

    NullReferenceException NullPointerException

        3
  •  2
  •   Lie Ryan Bryan    14 年前

    myclass *p = NULL;
    *p = ...;  // illegal: dereferencing NULL pointer
    ... = *p;  // illegal: dereferencing NULL pointer
    p->meth(); // illegal: equivalent to (*p).meth(), which is dereferencing NULL pointer
    
    myclass *p = /* some legal, non-NULL pointer */;
    *p = ...;  // Ok
    ... = *p;  // Ok
    p->meth(); // Ok, if myclass::meth() exists
    

    (*p) p->... (*p). ...

        4
  •  0
  •   Prasoon Saurav    14 年前

    wiki


    int val =1;
    int *p = NULL;
    *p = val; // Whooosh!!!! 
    
        5
  •  0
  •   Arun    14 年前

    wikipedia

    作为 取消引用 指针。

    取消引用是通过应用 unary * 指针上的运算符。

    int x = 5;
    int * p;      // pointer declaration
    p = &x;       // pointer assignment
    *p = 7;       // pointer dereferencing, example 1
    int y = *p;   // pointer dereferencing, example 2
    

    “取消对空指针的引用”表示执行 *p p NULL