Chapter Two
Chapter Two
Pointers in C+
+
What is Pointer?
• In C++, pointers are variables that store the
memory addresses of other variables.
• It is also known as locator or indicator that points
to an address of a value.
• Pointers are symbolic representations of
addresses.
• The address of the variable you’re working with is
assigned to the pointer variable that points to the
same data type (such as an int or string).
• Every variable we declare in our program has an
associated location in the memory, which we call
the memory address of the variable.
Cont.
• A pointer variable points to a data type (like int or
string) of the same type, and is created with the
* operator.
• The address of the variable you're working with
is assigned to the pointer.
• Example:
Cont.
• Here, 0x at the beginning represents the address in the
hexadecimal form.
• Notice that the first address differs from the second by 4 bytes, and the
second address differs from the third by 4 bytes, and so forth if we had
many variables.
• The difference is because the size of an int is 4 bytes in a 64-bit system.
• Note: You may not get the same results when you run the program.
This is because the address depends on the environment in which the
program runs.
• When we explain the previous slide program:
o We created a pointer variable with the name ptr, that
points to a string variable, by using the asterisk sign *
(string* ptr).
Note that the type of the pointer has to match the type of the
variable we are working with.
o We used the & operator to store the memory address of
the variable called stud, and assign it to the pointer.
o Now, ptr holds the value of stud’s memory address.
Questions
1. What does a pointer store in C++?
A. The memory address of another variable
B. The value of another variable
C. The data type of another variable
D. The size of a variable