Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 14

Pointers

Pointer

• a pointer is a programming language object, whose value refers to (or


"points to") another value stored elsewhere in the computer memory using
its memory address.
• A pointer references a location in memory, and obtaining the value stored at
that location is known as dereferencing the pointer.
Advantages

• By using pointers you can access a data which is available outside a


function.
• By using pointer variable we can implement dynamic memory allocation.
• With the help of pointer we can handle any type of data structure.
• Pointers can increase the execution speed of program.
Sample program
#include <iostream>
using namespace std;
int main()
{
int value;
cout << "Value lives at “ << &value;

cout << "\n\n";


system("pause");
return 0;
}
form
datatype *pointername
#include <iostream>
using namespace std;
declaration
int main()
example {
int value;
int *pointer;

cout << "Value lives at " << &value << "\n";


cout << "Pointer lives at " << &pointer;

cout << "\n\n";

return 0;
}
Initialization #include <iostream>
using namespace std;
int main()
{
int value = 12;
int *pointer = &value;
cout << "Value lives at: " << value << "\n";
cout << "Pointer lives at: " << *pointer;
cout << "\n\n";
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int value;
int *pointer;
pointer = &value;
Value = 26;
cout << "Value = " << value << "\n";
cout << "*Pointer = " << *pointer << "\n";
cout << "\n";
return 0;

}
Activity 1
#include <iostream>
using namespace std;
int main()
{
int var1 = 3;
int var2 = 24;
int var3 = 17;
cout << &var1 << endl;
cout << &var2 << endl;
cout << &var3 << endl;
}
Pointer to Pointer

• Instead of pointing to a regular variable, a pointer can be made to point to


another pointer.
• To apply this, always remember that you must specify what target a pointer
is pointing to.
Example: #include <iostream>
using namespace std;
int main()
{
int x = 26;
int *y;
int **z;
y = &x;
z = &y;
cout << " Value = " << x << "\n";
cout << " *Pointer = " << *y<< "\n";
cout << "**Pointer = " << **z<< "\n";
return 0;
}
cout << " Value = " << value << "\n";
Another example: cout << " *Pointer = " << *pointer << "\n";
cout << "**Pointer = " << **pointerToPointer <<
"\n";
#include <iostream>
value = 4805;
using namespace std;
int main()
cout << "After changing the value of the main
{ variable...\n";
int value = 26; cout << " Value = " << value << "\n";
int *pointer; cout << " *Pointer = " << *pointer << "\n";
int **pointerToPointer; cout << "**Pointer = " << **pointerToPointer <<
"\n";
pointer = &value;
return 0;
pointerToPointer = &pointer;
}

You might also like