difference between pointer and reference in c?

前端 未结 9 1542
傲寒
傲寒 2020-12-25 08:11

what is the difference between pointer , reference and dereference in c?

9条回答
  •  自闭症患者
    2020-12-25 09:15

    Referencing means taking the address of an existing variable (using &) to set a pointer variable. In order to be valid, a pointer has to be set to the address of a variable of the same type as the pointer, without the asterisk:

    int  c1;
    int* p1;
    c1 = 5;
    p1 = &c1;
    //p1 references c1
    

    Dereferencing a pointer means using the * operator (asterisk character) to access the value stored at a pointer: NOTE: The value stored at the address of the pointer must be a value OF THE SAME TYPE as the type of variable the pointer "points" to, but there is no guarantee this is the case unless the pointer was set correctly. The type of variable the pointer points to is the type less the outermost asterisk.

    int n1;
    n1 = (*p1);
    

    Invalid dereferencing may or may not cause crashes:

    Any dereferencing of any uninitialized pointer can cause a crash Dereferencing with an invalid type cast will have the potential to cause a crash. Dereferencing a pointer to a variable that was dynamically allocated and was subsequently de-allocated can cause a crash Dereferencing a pointer to a variable that has since gone out of scope can also cause a crash. Invalid referencing is more likely to cause compiler errors than crashes, but it's not a good idea to rely on the compiler for this.

    References:

    http://www.codingunit.com/cplusplus-tutorial-pointers-reference-and-dereference-operators

    & is the reference operator and can be read as “address of”.
    * is the dereference operator and can be read as “value pointed by”.
    

    http://www.cplusplus.com/doc/tutorial/pointers/

    & is the reference operator    
    * is the dereference operator
    

    you can read wiki as well The dereference operator * is also called the indirection operator.

    This text is taken from this link they have provided the same answer to the same question: meaning of "referencing" and "dereferencing"

提交回复
热议问题