translate the following to vietnamese: 5. Memory Address: A pointer has its own memory…
- User
translate the following to vietnamese: 5. Memory Address: A pointer has its own memory address and size on the stack, whereas a reference shares the same memory address with the original variable and takes up no space on the stack.
int &p = a; cout << &p << endl << &a;
-
NULL value: A pointer can be assigned NULL directly, whereas a reference cannot be. The constraints associated with references (no NULL, no reassignment) ensure that the underlying operations do not run into an exception situation.
-
Indirection: You can have a pointer to pointer (known as a double pointer) offering extra levels of indirection, whereas references only offer one level of indirection. For example,
In Pointers, int a = 10; int *p; int **q; // It is valid. p = &a; q = &p;
// Whereas in references, int &p = a; int &&q = p; // It is reference to reference, so it is an error
- Arithmetic operations: Various arithmetic operations can be performed on pointers, whereas there is no such thing called Reference Arithmetic (however, you can perform pointer arithmetic on the address of an object pointed to by a reference, as in &obj + 5).
Tabular form of difference between References and Pointers in C++ References Pointers Reassignment The variable cannot be reassigned in Reference. The variable can be reassigned in Pointers. Memory Address It shares the same address as the original variable. Pointers have their own memory address. Work It is referring to another variable. It is storing the address of the variable. Null Value It does not have null value. It can have value assigned as null. Arguments This variable is referenced by the method pass by value. The pointer does it work by the method known as pass by reference. When to use What
The performances are exactly the same as references are implemented internally as pointers. But still, you can keep some points in your mind to decide when to use what:
Use references: In function parameters and return types. Use pointers: If pointer arithmetic or passing a NULL pointer is needed. For example, for arrays (Note that accessing an array is implemented using pointer arithmetic). To implement data structures like a linked list, a tree, etc. and their algorithms. This is so because, in order to point to different cells, we have to use the concept of pointers.
-
- Assistant
- Địa chỉ bộ nhớ: Con trỏ có địa chỉ và kích thước bộ nhớ riêng trên ngăn xếp, trong khi tham chiếu chia sẻ cùng địa chỉ bộ nhớ với biến gốc và không chiếm không gian trên ngăn xếp.
int &p = a; cout << &p << endl << &a;
-
Giá trị NULL: Con trỏ có thể được gán trực tiếp NULL, trong khi tham chiếu không thể. Các ràng buộc liên quan đến tham chiếu (không có NULL, không có gán lại) đảm bảo các hoạt động cơ bản không gây ra tình huống ngoại lệ.