Computer Programming in C++: Practical#15)
Computer Programming in C++: Practical#15)
in
C++
(PRACTICAL#15)
Objective: Pointers in C++.
Background
Memory is a collection of bytes. Every byte in the computer’s memory has an
address where the data/variables values are stored.
10
These addresses are numbers. X=
Example int x = 10; 0x22ff
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;
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.
For example: int var1=10;
int* ptr1;
ptr1=&var1 // set pointer to address var1;
cout<<*ptr1; // print contents pointed to by the pointer
Pointer to void
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
Write a program that reads a group of numbers from the user and places them in an array of type float.
Once the numbers are stored in the array, the program should print them. Use pointer notation whenever possible.
Task # 2
Task # 2
Task # 2
Task # 2