C++ Pointer

We need your feedback. Click here!
- A pointer is a parameter that contains the address of an existing variable or object.
- A pointer to an existing data type variable can be defined and initialized as follows:
datatype* ptr_name = &variable_name;- A pointer to an existing datatype variable can be defined and initialized as follows:
datatype* ptr_name = array_variable_name;- A pointer address can be represented by
std::cout << ptr_name;- The contents of a pointer address can be displayed by
std::cout << *ptr_name;
- The image above contains the following information:
- In I), an integer variable is initialized and stores the value 2022. The x_ptr pointer is initialized to the address of variable x. Consequently, the given value x can be accessed via the x_ptr pointer and *x_ptr.
- In II), the value stored by x is doubled using a pointer. First, the previous contents of x (*x_ptr) are accessed, then doubled by *x_ptr * 2. The resulting new value is stored in the location pointed to by x_ptr, which is the variable x with *x_ptr = *x_ptr * 2. Thus, std :: cout x would display 4044 instead of 2022.
- In III), an integer table of x is initialized with the values 2, 4 and 3. The pointer x_ptr to this table is initialized with int* x_ptr = x . x_ptr points to the address of the element at index 0. Since the elements of the table are stored in order in memory, x_ptr or x_ptr+0, x_ptr+1, x_ptr+2, ..., x_ptr+n gives you the addresses of elements at index 0, 1, 2, ..., n for a table of size n+1. The element at index n is accessed by *(x_ptr+n).
- In IV), the element at index 2 of column x is set to 5 and *(x_ptr+2) = 5.
Our company offers online and in-person C++ training. Register now and join the community.
References
[1] "Pointer declaration": http://thbecker.net/articles/rvalue_references/section_01.html