Beruflich Dokumente
Kultur Dokumente
in
C++
(PRACTICAL#10)
Objective: Pointers in C++
Introduction
Memory is a collection of bytes. Every byte in the computer’s memory has an
address where the data/variables values are stored.
These addresses are numbers. X= 10
You can find the address occupied by a variable by using the address-of operator.
The address of a variable can be obtained by preceding the name of a variable with an
ampersand sign (&), known as address-of operator. For example:
Example int var1 = 10;
Cout<<&var1 // print the address of var1
Remember that the address of a variable is not the same as its
contents
The 0x in the beginning represents the address is in hexadecimal form.
You can find the address occupied by a variable by using the address-of operator.
Example
int var1 = 10; Memory Representation
int var2=20; Addresses
cout<<&var1; var1 10 ff0
cout<<&var2; var2 20 ff2
Pointer Variables
Examples
It makes possible to return more than one value from the function.
Reference operator (&) and Deference operator (*)
Referencing means taking the address of an existing variable (using &) to set a pointer
variable.
Example
int var1=10;
char ch=‘a’;
int* ptr1;
char* prt2;
To get the value stored in the memory address, we use the dereference operator (*).
Dereferencing a pointer means using the * operator (asterisk character) to
access the value stored at a pointer:
Dereferencing means access value of a variable pointed to by the pointer.
The address that you want to put in a pointer must be the same type as the pointer,
You can’t assign the address of a float variable to a pointer to int. For example
float f=10.25;
Int* ptr=&f; // ERROR: can’t assign float * to int *
Pointer to void is a general-purpose pointer that can point to any data type.
You can assign one kind of pointer type to another by using reinterpret_cast.
Example
float f=10.25;
Int* ptr;
ptr=reinterpret_cast<int*>(f);
Tasks for Lab #
Task # 1
Task # 2
Write a program that asks the user to enter integers as inputs to be stored in the variables 'a' and 'b' respectively. There are
also two integer pointers named ptrA and ptrB. Assign the values of 'a' and 'b' to ptrA and ptrB respectively, and display
them.
Task # 3
Write a program that reads a group of numbers from the user and places them in an array of type int.
Once the numbers are stored in the array, the program should print them. Use pointer notation whenever possible.