SlideShare a Scribd company logo
1 of 21
By Barbara Thompson Updated August 25, 2022
In C++, a pointer refers to a variable that holds the address of another
variable. Like regular variables, pointers have a data type. For example, a
pointer of type integer can hold the address of a variable of type integer. A
pointer of character type can hold the address of a variable of character type.
You should see a pointer as a symbolic representation of a memory address.
With pointers, programs can simulate call-by-reference. They can also create
and manipulate dynamic data structures. In C++, a pointer variable refers to a
variable pointing to a specific address in a memory pointed by another
variable.
In this C++ tutorial, you will learn:
What are Pointers?
Addresses in C++
Pointer Declaration Syntax
Reference operator (&) and Deference operator (*)
Pointers and Arrays
NULL Pointer
Pointers of Variables
Application of Pointers
Advantages of using Pointers
To understand C++ pointers, you must understand how computers store data.
When you create a variable in your C++ program, it is assigned some space the computer memory. The value of this variable
is stored in the assigned location.
To know the location in the computer memory where the data is stored, C++ provides the (reference) operator. The
operator returns the address that a variable occupies.
For example, if x is a variable, &x returns the address of the variable.
EXPLORE MORE
Learn Java Programming
with Beginners Tutorial
08:32
Linux Tutorial for
Beginners: Introduction
to Linux Operating...
04:56 35:04
The declaration of C++ takes the following syntax:
datatype *variable_name;
The datatype is the base type of the pointer which must be a valid C++ data type.
The variable_name is should be the name of the pointer variable.
Asterisk used above for pointer declaration is similar to asterisk used to perform multiplication operation. It is the
asterisk that marks the variable as a pointer.
Here is an example of valid pointer declarations in C++:
int *x; // a pointer to integer
double *x; // a pointer to double
float *x;
char *ch
// a pointer to float
// a pointer to a character
The reference operator (&) returns the variable’s address.
The dereference operator (*) helps us get the value that has been stored in a memory address.
For example:
If we have a variable given the name num, stored in the address 0x234 and storing the value 28.
The reference operator (&) will return 0x234.
The dereference operator (*) will return 5.
#include <iostream>
using namespace std;
int main() {
int x = 27;
int *ip;
ip = &x;
cout << "Value of x is : ";
cout << x << endl;
cout << "Value of ip is : ";
cout << ip<< endl;
cout << "Value of *ip is : ";
cout << *ip << endl;
return 0;
}
How this works:
Here is a screenshot of the code:
1. Import the iostream header file. This will allow us to use the functions defined in the header file without getting errors.
2. Include the std namespace to use its classes without calling it.
3. Call the main() function. The program logic should be added within the body of this function. The { marks the beginning
of the function’s body.
4. Declare an integer variable x and assigning it a value of 27.
5. Declare a pointer variable *ip.
6. Store the address of variable x in the pointer variable.
7. Print some text on the console.
8. Print the value of variable x on the screen.
9. Print some text on the console.
10. Print the address of variable x. The value of the address was stored in the variable ip.
11. Print some text on the console.
12. Print value of stored at the address of the pointer.
13. The program should return value upon successful execution.
14. End of the body of the main() function.
Arrays and pointers work based on a related concept. There are di erent things to note when working with arrays having
pointers. The array name itself denotes the base address of the array. This means that to assign the address of an array to a
pointer, you should not use an ampersand (&).
For example:
p = arr;
The above is correct since arr represents the arrays’ address. Here is another example:
p = &arr;
We can implicitly convert an array into a pointer. For example:
int arr [20];
int * ip;
Below is a valid operation:
ip = arr;
A er the above declaration, ip and arr will be equivalent, and they will share properties. However, a di erent address can be
assigned to ip, but we cannot assign anything to arr.
This example shows how to traverse an array using pointers:
#include <iostream>
using namespace std;
int main() {
int *ip;
int arr[] = { 10, 34, 13, 76, 5, 46 };
ip = arr;
for (int x = 0; x < 6; x++) {
cout << *ip << endl;
ip++;
}
return 0;
}
Here is a screenshot of the code:
1. Declare an integer pointer variable ip.
2. Declare an array named arr and store 6 integers into it.
3. Assign arr to ip. The ip and arr will become equivalent.
4. Create a for a loop. The loop variable x was created to iterate over the array elements from index 0 to 5.
5. Print the values stored at the address of the pointer IP. One value will be returned per iteration, and a total of 6
repetitions will be done. The endl is a C++ keyword that means the end line. This action allows you to moves the cursor
to the next line a er each value is printed. Each value will be printed in an individual line.
6. To move the pointer to the next int position a er every iteration.
7. End of the for a loop.
8. The program must return something upon successful execution.
9. End of the main() function body.
If there is no exact address that is to be assigned, then the pointer variable can be assigned a NULL. It should be done during
the declaration. Such a pointer is known as a null pointer. Its value is zero and is defined in manystandard libraries like
iostream.
#include <iostream>
using namespace std;
int main() {
int *ip = NULL;
cout << "Value of ip is: " << ip;
return 0;
}
Here is a screenshot of the code:
1. Declare a pointer variable ip and assigning it a value of NULL.
2. Print value of pointer variable ip alongside some text on the console.
3. The program must return value upon successful completion.
4. End of the body of the main() function.
With C++, you can manipulate data directly from the computer’s memory.
The memory space can be assigned or re-assigned as one wishes. This is made possible byPointer variables.
Pointer variables point to a specific address in the computer’s memory pointed to by another variable.
It can be declared as follows:
int *p;
Or,
int* p;
In the you example, we have declared the pointer variable p.
It will hold a memory address.
The asterisk is the dereference operator that means a pointer to.
The pointer p is pointing to an integer value in the memory address.
#include <iostream>
using namespace std;
int main() {
int *p, x = 30;
p = &x;
cout << "Value of x is: " << *p;
return 0;
}
Here is a screenshot of the code:
1. Declare a pointer variable p and a variable x with a value of 30.
2. Assign the address of variable x to p.
3. Print the value of pointer variable p alongside some text on the console.
4. The program must return value upon successful completion.
5. End of the body of the main() function.
Functions in C++ can return only one value. Further, all the variables declared in a function are allocated on the function call
stack. As soon as the function returns, all the stack variables are destroyed.
Arguments to function are passed by value, and any modification done on the variables doesn’t change the value of the
actual variables that are passed. Following example helps illustrate this concept:-
Example 5:
#include <iostream>
using namespace std;
void test(int*, int*);
int main() {
int a = 5, b = 5;
cout << "Before changing:" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
test(&a, &b);
cout << "nAfter changing" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}
void test(int* n1, int* n2) {
*n1 = 10;
*n2 = 11;
}
Here is a screenshot of the code:
1. Create a prototype of a function named test that will take two integer parameters.
2. Call the main() function. We will add the program logic inside its body.
3. Declare two integer variables a and b,each with a value of 5.
4. Print some text on the console. The endl (end line) will move the cursor to begin printing in the next line.
5. Print the value of variable a on the console alongside other text. The endl (end line) will move the cursor to begin
printing in the next line.
6. Print the value of variable b on the console alongside other text. The endl (end line) will move the cursor to begin
printing in the next line.
7. Create a function named test() that takes in the addresses of variable a and b as the parameters.
8. Print some text on the console. The n will create a new blank line before the text is printed. The endl (end line) will
move the cursor to begin printing in the next line a er the text is printed.
9. Print the value of variable a on the console alongside other text. The endl (end line) will move the cursor to begin
printing in the next line.
10. Print the value of variable b on the console alongside other text. The endl (end line) will move the cursor to begin
printing in the next line.
11. The program must return value upon successful completion.
12. End of the body of the main() function.
13. Defining the function test(). The function should take two integer pointer variables *n1 and *n2.
14. Assigning the pointer variable *n1 a value of 10.
15. Assigning the pointer variable *n2 a value of 11.
16. End of the body of the function test().
Even Though,new values are assigned to variable a and b inside the function test, once the function call completes, the
same is not reflected the outer function main.
Using pointers as function arguments helps to pass the variable’s actual address in the function, and all the changes
performed on the variable will be reflected in the outer function.
In the above case, the function ‘test’ has the address of variables ‘a’ and ‘b.’ These two variables are directly accessible from
the function ‘test’, and hence any change done to these variables are reflected in the caller function ‘main.’
Here, are pros/benefits of using Pointers
Pointers are variables which store the address of other variables in C++.
More than one variable can be modified and returned by function using pointers.
Memory can be dynamically allocated and de-allocated using pointers.
Pointers help in simplifying the complexity of the program.
The execution speed of a program improves byusing pointers.
A pointer refers to a variable holding address of another variable.
Each pointer has a valid data type.
A pointer is a symbolic representation of a memory address.
Pointers allow programs to simulate call-by-reference and create and manipulate dynamic data structures.
Arrays and pointers use a related concept.
The array name denotes the array’s base.
If you want to assign the address of an array to a pointer, don’t use an ampersand (&).
If there is no specific address to assign a pointer variable, assign it a NULL.
Prev Reporta Bug Next
About Us
Advertise with Us
Write For Us
Contact Us
SAP Career Suggestion Tool
So ware Testing as a Career
eBook
Blog
Quiz
SAP eBook
Execute Java Online
Execute Javascript
Execute HTML
Execute Python
© Copyright - Guru99 2022 Privacy Policy | A iliate Disclaimer | ToS

More Related Content

Similar to C++ Pointers with Examples.docx

Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloadingankush_kumar
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxShashiShash2
 
1. DSA - Introduction.pptx
1. DSA - Introduction.pptx1. DSA - Introduction.pptx
1. DSA - Introduction.pptxhara69
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1AmIt Prasad
 
Unit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptxUnit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptxajajkhan16
 
VIT351 Software Development VI Unit3
VIT351 Software Development VI Unit3VIT351 Software Development VI Unit3
VIT351 Software Development VI Unit3YOGESH SINGH
 
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdfEASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdfsudhakargeruganti
 
chapter-7 slide.pptx
chapter-7 slide.pptxchapter-7 slide.pptx
chapter-7 slide.pptxcricketreview
 
Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)tech4us
 
c++ pointers by Amir Hamza Khan (SZABISTIAN)
c++ pointers by Amir Hamza Khan (SZABISTIAN)c++ pointers by Amir Hamza Khan (SZABISTIAN)
c++ pointers by Amir Hamza Khan (SZABISTIAN)Ameer Hamxa
 

Similar to C++ Pointers with Examples.docx (20)

Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
 
PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
 
1. DSA - Introduction.pptx
1. DSA - Introduction.pptx1. DSA - Introduction.pptx
1. DSA - Introduction.pptx
 
Functions in C++.pdf
Functions in C++.pdfFunctions in C++.pdf
Functions in C++.pdf
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
 
Unit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptxUnit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptx
 
Pointers
PointersPointers
Pointers
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
C Programming Unit-4
C Programming Unit-4C Programming Unit-4
C Programming Unit-4
 
VIT351 Software Development VI Unit3
VIT351 Software Development VI Unit3VIT351 Software Development VI Unit3
VIT351 Software Development VI Unit3
 
Pointers
PointersPointers
Pointers
 
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdfEASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
 
chapter-7 slide.pptx
chapter-7 slide.pptxchapter-7 slide.pptx
chapter-7 slide.pptx
 
Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)
 
c++ pointers by Amir Hamza Khan (SZABISTIAN)
c++ pointers by Amir Hamza Khan (SZABISTIAN)c++ pointers by Amir Hamza Khan (SZABISTIAN)
c++ pointers by Amir Hamza Khan (SZABISTIAN)
 
C function
C functionC function
C function
 
Pointers
PointersPointers
Pointers
 

Recently uploaded

Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayMakMakNepo
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 

Recently uploaded (20)

Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up Friday
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 

C++ Pointers with Examples.docx

  • 1. By Barbara Thompson Updated August 25, 2022 In C++, a pointer refers to a variable that holds the address of another variable. Like regular variables, pointers have a data type. For example, a pointer of type integer can hold the address of a variable of type integer. A pointer of character type can hold the address of a variable of character type. You should see a pointer as a symbolic representation of a memory address. With pointers, programs can simulate call-by-reference. They can also create and manipulate dynamic data structures. In C++, a pointer variable refers to a variable pointing to a specific address in a memory pointed by another variable. In this C++ tutorial, you will learn: What are Pointers? Addresses in C++ Pointer Declaration Syntax Reference operator (&) and Deference operator (*) Pointers and Arrays NULL Pointer Pointers of Variables
  • 2. Application of Pointers Advantages of using Pointers To understand C++ pointers, you must understand how computers store data. When you create a variable in your C++ program, it is assigned some space the computer memory. The value of this variable is stored in the assigned location. To know the location in the computer memory where the data is stored, C++ provides the (reference) operator. The operator returns the address that a variable occupies. For example, if x is a variable, &x returns the address of the variable. EXPLORE MORE Learn Java Programming with Beginners Tutorial 08:32 Linux Tutorial for Beginners: Introduction to Linux Operating... 04:56 35:04 The declaration of C++ takes the following syntax:
  • 3. datatype *variable_name; The datatype is the base type of the pointer which must be a valid C++ data type. The variable_name is should be the name of the pointer variable. Asterisk used above for pointer declaration is similar to asterisk used to perform multiplication operation. It is the asterisk that marks the variable as a pointer. Here is an example of valid pointer declarations in C++: int *x; // a pointer to integer double *x; // a pointer to double float *x; char *ch // a pointer to float // a pointer to a character The reference operator (&) returns the variable’s address. The dereference operator (*) helps us get the value that has been stored in a memory address. For example: If we have a variable given the name num, stored in the address 0x234 and storing the value 28. The reference operator (&) will return 0x234.
  • 4. The dereference operator (*) will return 5. #include <iostream> using namespace std; int main() { int x = 27; int *ip; ip = &x; cout << "Value of x is : "; cout << x << endl; cout << "Value of ip is : "; cout << ip<< endl; cout << "Value of *ip is : "; cout << *ip << endl; return 0; } How this works:
  • 5. Here is a screenshot of the code:
  • 6. 1. Import the iostream header file. This will allow us to use the functions defined in the header file without getting errors. 2. Include the std namespace to use its classes without calling it. 3. Call the main() function. The program logic should be added within the body of this function. The { marks the beginning of the function’s body. 4. Declare an integer variable x and assigning it a value of 27. 5. Declare a pointer variable *ip.
  • 7. 6. Store the address of variable x in the pointer variable. 7. Print some text on the console. 8. Print the value of variable x on the screen. 9. Print some text on the console. 10. Print the address of variable x. The value of the address was stored in the variable ip. 11. Print some text on the console. 12. Print value of stored at the address of the pointer. 13. The program should return value upon successful execution. 14. End of the body of the main() function. Arrays and pointers work based on a related concept. There are di erent things to note when working with arrays having pointers. The array name itself denotes the base address of the array. This means that to assign the address of an array to a pointer, you should not use an ampersand (&). For example: p = arr; The above is correct since arr represents the arrays’ address. Here is another example: p = &arr;
  • 8. We can implicitly convert an array into a pointer. For example: int arr [20]; int * ip; Below is a valid operation: ip = arr; A er the above declaration, ip and arr will be equivalent, and they will share properties. However, a di erent address can be assigned to ip, but we cannot assign anything to arr. This example shows how to traverse an array using pointers: #include <iostream> using namespace std; int main() { int *ip; int arr[] = { 10, 34, 13, 76, 5, 46 }; ip = arr; for (int x = 0; x < 6; x++) {
  • 9. cout << *ip << endl; ip++; } return 0; } Here is a screenshot of the code:
  • 10. 1. Declare an integer pointer variable ip. 2. Declare an array named arr and store 6 integers into it. 3. Assign arr to ip. The ip and arr will become equivalent. 4. Create a for a loop. The loop variable x was created to iterate over the array elements from index 0 to 5.
  • 11. 5. Print the values stored at the address of the pointer IP. One value will be returned per iteration, and a total of 6 repetitions will be done. The endl is a C++ keyword that means the end line. This action allows you to moves the cursor to the next line a er each value is printed. Each value will be printed in an individual line. 6. To move the pointer to the next int position a er every iteration. 7. End of the for a loop. 8. The program must return something upon successful execution. 9. End of the main() function body. If there is no exact address that is to be assigned, then the pointer variable can be assigned a NULL. It should be done during the declaration. Such a pointer is known as a null pointer. Its value is zero and is defined in manystandard libraries like iostream. #include <iostream> using namespace std; int main() { int *ip = NULL; cout << "Value of ip is: " << ip; return 0; }
  • 12. Here is a screenshot of the code: 1. Declare a pointer variable ip and assigning it a value of NULL. 2. Print value of pointer variable ip alongside some text on the console. 3. The program must return value upon successful completion. 4. End of the body of the main() function. With C++, you can manipulate data directly from the computer’s memory. The memory space can be assigned or re-assigned as one wishes. This is made possible byPointer variables. Pointer variables point to a specific address in the computer’s memory pointed to by another variable. It can be declared as follows:
  • 13. int *p; Or, int* p; In the you example, we have declared the pointer variable p. It will hold a memory address. The asterisk is the dereference operator that means a pointer to. The pointer p is pointing to an integer value in the memory address. #include <iostream> using namespace std; int main() { int *p, x = 30; p = &x; cout << "Value of x is: " << *p; return 0; }
  • 14. Here is a screenshot of the code: 1. Declare a pointer variable p and a variable x with a value of 30. 2. Assign the address of variable x to p. 3. Print the value of pointer variable p alongside some text on the console.
  • 15. 4. The program must return value upon successful completion. 5. End of the body of the main() function. Functions in C++ can return only one value. Further, all the variables declared in a function are allocated on the function call stack. As soon as the function returns, all the stack variables are destroyed. Arguments to function are passed by value, and any modification done on the variables doesn’t change the value of the actual variables that are passed. Following example helps illustrate this concept:- Example 5: #include <iostream> using namespace std; void test(int*, int*); int main() { int a = 5, b = 5; cout << "Before changing:" << endl; cout << "a = " << a << endl; cout << "b = " << b << endl; test(&a, &b); cout << "nAfter changing" << endl; cout << "a = " << a << endl; cout << "b = " << b << endl; return 0;
  • 16. } void test(int* n1, int* n2) { *n1 = 10; *n2 = 11; } Here is a screenshot of the code:
  • 17. 1. Create a prototype of a function named test that will take two integer parameters. 2. Call the main() function. We will add the program logic inside its body. 3. Declare two integer variables a and b,each with a value of 5.
  • 18. 4. Print some text on the console. The endl (end line) will move the cursor to begin printing in the next line. 5. Print the value of variable a on the console alongside other text. The endl (end line) will move the cursor to begin printing in the next line. 6. Print the value of variable b on the console alongside other text. The endl (end line) will move the cursor to begin printing in the next line. 7. Create a function named test() that takes in the addresses of variable a and b as the parameters. 8. Print some text on the console. The n will create a new blank line before the text is printed. The endl (end line) will move the cursor to begin printing in the next line a er the text is printed. 9. Print the value of variable a on the console alongside other text. The endl (end line) will move the cursor to begin printing in the next line. 10. Print the value of variable b on the console alongside other text. The endl (end line) will move the cursor to begin printing in the next line. 11. The program must return value upon successful completion. 12. End of the body of the main() function. 13. Defining the function test(). The function should take two integer pointer variables *n1 and *n2. 14. Assigning the pointer variable *n1 a value of 10. 15. Assigning the pointer variable *n2 a value of 11. 16. End of the body of the function test(). Even Though,new values are assigned to variable a and b inside the function test, once the function call completes, the same is not reflected the outer function main. Using pointers as function arguments helps to pass the variable’s actual address in the function, and all the changes performed on the variable will be reflected in the outer function. In the above case, the function ‘test’ has the address of variables ‘a’ and ‘b.’ These two variables are directly accessible from the function ‘test’, and hence any change done to these variables are reflected in the caller function ‘main.’
  • 19. Here, are pros/benefits of using Pointers Pointers are variables which store the address of other variables in C++. More than one variable can be modified and returned by function using pointers. Memory can be dynamically allocated and de-allocated using pointers. Pointers help in simplifying the complexity of the program. The execution speed of a program improves byusing pointers. A pointer refers to a variable holding address of another variable. Each pointer has a valid data type. A pointer is a symbolic representation of a memory address. Pointers allow programs to simulate call-by-reference and create and manipulate dynamic data structures. Arrays and pointers use a related concept. The array name denotes the array’s base. If you want to assign the address of an array to a pointer, don’t use an ampersand (&). If there is no specific address to assign a pointer variable, assign it a NULL.
  • 20. Prev Reporta Bug Next About Us Advertise with Us Write For Us Contact Us SAP Career Suggestion Tool So ware Testing as a Career eBook Blog Quiz SAP eBook Execute Java Online
  • 21. Execute Javascript Execute HTML Execute Python © Copyright - Guru99 2022 Privacy Policy | A iliate Disclaimer | ToS