SlideShare une entreprise Scribd logo
1  sur  11
C++ Array Types
There are 2 types of arrays in C++ programming:
1. Single Dimensional Array
2.
3. Multidimensional Array
C++ Single Dimensional Array
Let's see a simple example of C++ array, where we are going to create, initialize and traverse
array.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
6. //traversing array
7. for (int i = 0; i < 5; i++)
8. {
9. cout<<arr[i]<<"n";
10. }
11. }
Output:/p>
10
0
20
0
30
C++ Array Example: Traversal using foreach loop
We can also traverse the array elements using foreach loop. It returns array element one by
one.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
6. //traversing array
7. for (int i: arr)
8. {
9. cout<<i<<"n";
10. }
11. }
Output:
10
20
30
40
50
C++ Structs
In C++, classes and structs are blueprints that are used to create instance of a class.
Structs are used for lightweight objects such as Rectangle, color, Point etc.
Unlike class, structs in C++ are value type than reference type. It is useful if you have
data that is not intended to be modified after creation of struct.
C++ Struct Example
Let's see a simple example of struct Rectangle which has two data members widt h and
height.
1. #include <iostream>
2. using namespace std;
3. struct Rectangle
4. {
5. int width, height;
6.
7. };
8. int main(void) {
9. struct Rectangle rec;
10. rec.width=8;
11. rec.height=5;
12. cout<<"Area of Rectangle is: "<<(rec.width * rec.height)<<endl;
13. return 0;
14. }
Output:
Area of Rectangle is: 40
C++ Struct Example: Using Constructor and Method
Let's see another example of struct where we are using constructor to initialize data and
method to calculate area of rectangle.
1. #include <iostream>
2. using namespace std;
3. struct Rectangle
4. {
5. int width, height;
6. Rectangle(int w, int h)
7. {
8. width = w;
9. height = h;
10. }
11. void areaOfRectangle() {
12. cout<<"Area of Rectangle is: "<<(width*height); }
13. };
14. int main(void) {
15. struct Rectangle rec=Rectangle(4,6);
16. rec.areaOfRectangle();
17. return 0;
18. }
Output:
Area of Rectangle is: 24
C++ Pointers
The pointer in C++ language is a variable, it is also known as locator or indicator that points
to an address of a value.
Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings,
trees etc. and used with arrays, structures and functions.
2) We can return multiple values from function using pointer.
3) It makes you able to access any memory location in the computer's memory.
Usage of pointer
There are many usage of pointers in C++ language.
1) Dynamic memory allocation
In c language, we can dynamically allocate memory using malloc() and calloc() functions
where pointer is used.
2) Arrays, Functions and Structures
Pointers in c language are widely used in arrays, functions and structures. It reduces the code
and improves the performance.
Symbols used in pointer
Symbol Name Description
& (ampersand sign) Address operator Determine the address
∗ (asterisk sign) Indirection operator Access the value of an
Declaring a pointer
The pointer in C++ language can be declared using ∗ (asterisk symbol).
1. int ∗ a; //pointer to int
2. char ∗ c; //pointer to char
Pointer Example
Let's see the simple example of using pointers printing the address and value.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int number=30;
6. int ∗ p;
7. p=&number;//stores the address of number variable
8. cout<<"Address of number variable is:"<<&number<<endl;
9. cout<<"Address of p variable is:"<<p<<endl;
10. cout<<"Value of p variable is:"<<*p<<endl;
11. return 0;
12. }
Output
Address of number variable is:0x7ffccc8724c4
Address of p variable is:0x7ffccc8724c4
Value of p variable is:30
Pointer Program to swap 2 numbers without using 3rd
variable
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=20,b=10,∗p1=&a,∗p2=&b;
6. cout<<"Before swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;
7. ∗p1=∗p1+∗p2;
8. ∗p2=∗p1-∗p2;
9. ∗p1=∗p1-∗p2;
10. cout<<"After swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;
11. return 0;
12. }
Output
Before swap: ∗p1=20 ∗p2=10
After swap: ∗p1=10 ∗p2=20
C++ Dynamic Memory
A good understanding of how dynamic memory really works in C++ is
essential to becoming a good C++ programmer. Memory in your C++
program is divided into two parts:
 The stack: All variables declared inside the function will take up memory from
the stack.
 The heap: This is unused memory of the program and can be used to allocate
the memory dynamically when program runs.
Many times, you are not aware in advance how much memory you will need
to store particular information in a defined variable and the size of required
memory can be determined at run time.
You can allocate memory at run time within the heap for the variable of a
given type using a special operator in C++ which returns the address of the
space allocated. This operator is called new operator.
If you are not in need of dynamically allocated memory anymore, you can
usedelete operator, which de-allocates memory previously allocated by new
operator.
The new and delete operators
There is following generic syntax to use new operator to allocate memory
dynamically for any data-type.
new data-type;
Here, data-type could be any built-in data type including an array or any
user defined data types include class or structure. Let us start with built-in
data types. For example we can define a pointer to type double and then
request that the memory be allocated at execution time. We can do this using
the newoperator with the following statements:
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
The memory may not have been allocated successfully, if the free store had
been used up. So it is good practice to check if new operator is returning
NULL pointer and take appropriate action as below:
double* pvalue = NULL;
if( !(pvalue = new double )) {
cout << "Error: out of memory." <<endl;
exit(1);
}
delete pvalue; // Release memory pointed to by pvalue
Let us put above concepts and form the following example to show how new
and delete work:
#include <iostream>
using namespace std;
int main () {
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
*pvalue = 29494.99; // Store value at allocated address
cout << "Value of pvalue : " << *pvalue << endl;
delete pvalue; // free up the memory.
return 0;
}
If we compile and run above code, this would produce the following result:
Value of pvalue : 29495
Dynamic Memory Allocation for Arrays
Consider you want to allocate memory for an array of characters, i.e., string
of 20 characters. Using the same syntax what we have used above we can
allocate memory dynamically as shown below.
char* pvalue = NULL; // Pointer initialized with null
pvalue = new char[20]; // Request memory for the variable
To remove the array that we have just created the statement would look like
this:
delete [] pvalue; // Delete array pointed to by pvalue
Following is the syntax of new operator for a multi-dimensional array as
follows:
int ROW = 2;
int COL = 3;
double **pvalue = new double* [ROW]; // Allocate memory for rows
// Now allocate memory for columns
for(int i = 0; i < COL; i++) {
pvalue[i] = new double[COL];
}
The syntax to release the memory for multi-dimensional will be as follows:
for(int i = 0; i < ROW; i++) {
delete[] pvalue[i];
}
delete [] pvalue;
Dynamic Memory Allocation for Objects
Objects are no different from simple data types. For example, consider the
following code where we are going to use an array of objects to clarify the
concept:
#include <iostream>
using namespace std;
class Box {
public:
Box() {
cout << "Constructor called!" <<endl;
}
~Box() {
cout << "Destructor called!" <<endl;
}
};
int main( ) {
Box* myBoxArray = new Box[4];
delete [] myBoxArray; // Delete array
return 0;
}
If you were to allocate an array of four Box objects, the Simple constructor
would be called four times and similarly while deleting these objects,
destructor will also be called same number of times.
If we compile and run above code, this would produce the following result:
Constructor called!
Constructor called!
Constructor called!
Constructor called!
Destructor called!
Destructor called!
Destructor called!
Destructor called!
Arrry structure Stacks  in data structure

Contenu connexe

Tendances

#OOP_D_ITS - 2nd - C++ Getting Started
#OOP_D_ITS - 2nd - C++ Getting Started#OOP_D_ITS - 2nd - C++ Getting Started
#OOP_D_ITS - 2nd - C++ Getting Started
Hadziq Fabroyir
 
C++totural file
C++totural fileC++totural file
C++totural file
halaisumit
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
Jussi Pohjolainen
 
FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2
rohassanie
 
#OOP_D_ITS - 3rd - Pointer And References
#OOP_D_ITS - 3rd - Pointer And References#OOP_D_ITS - 3rd - Pointer And References
#OOP_D_ITS - 3rd - Pointer And References
Hadziq Fabroyir
 

Tendances (20)

Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
 
This pointer
This pointerThis pointer
This pointer
 
Pointers+(2)
Pointers+(2)Pointers+(2)
Pointers+(2)
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 
C++ programming function
C++ programming functionC++ programming function
C++ programming function
 
#OOP_D_ITS - 2nd - C++ Getting Started
#OOP_D_ITS - 2nd - C++ Getting Started#OOP_D_ITS - 2nd - C++ Getting Started
#OOP_D_ITS - 2nd - C++ Getting Started
 
C++totural file
C++totural fileC++totural file
C++totural file
 
Pointer
PointerPointer
Pointer
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
 
FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2
 
#OOP_D_ITS - 3rd - Pointer And References
#OOP_D_ITS - 3rd - Pointer And References#OOP_D_ITS - 3rd - Pointer And References
#OOP_D_ITS - 3rd - Pointer And References
 
C++ tutorial
C++ tutorialC++ tutorial
C++ tutorial
 
Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
C++ references
C++ referencesC++ references
C++ references
 
Constructor in c++
Constructor in c++Constructor in c++
Constructor in c++
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 

Similaire à Arrry structure Stacks in data structure

18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator
SAFFI Ud Din Ahmad
 
C++ Course - Lesson 3
C++ Course - Lesson 3C++ Course - Lesson 3
C++ Course - Lesson 3
Mohamed Ahmed
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about Pointers
ANUSUYA S
 
C++ Pointers with Examples.docx
C++ Pointers with Examples.docxC++ Pointers with Examples.docx
C++ Pointers with Examples.docx
JoeyDelaCruz22
 

Similaire à Arrry structure Stacks in data structure (20)

18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator
 
C++ Course - Lesson 3
C++ Course - Lesson 3C++ Course - Lesson 3
C++ Course - Lesson 3
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about Pointers
 
C++_notes.pdf
C++_notes.pdfC++_notes.pdf
C++_notes.pdf
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
 
Link list
Link listLink list
Link list
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptx
 
Unit 3
Unit 3 Unit 3
Unit 3
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
LECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdfLECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdf
 
C++ Pointers with Examples.docx
C++ Pointers with Examples.docxC++ Pointers with Examples.docx
C++ Pointers with Examples.docx
 
LECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdfLECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdf
 
Chp4(ref dynamic)
Chp4(ref dynamic)Chp4(ref dynamic)
Chp4(ref dynamic)
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 

Dernier

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Dernier (20)

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 

Arrry structure Stacks in data structure

  • 1. C++ Array Types There are 2 types of arrays in C++ programming: 1. Single Dimensional Array 2. 3. Multidimensional Array C++ Single Dimensional Array Let's see a simple example of C++ array, where we are going to create, initialize and traverse array. 1. #include <iostream> 2. using namespace std; 3. int main() 4. { 5. int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array 6. //traversing array 7. for (int i = 0; i < 5; i++) 8. { 9. cout<<arr[i]<<"n"; 10. } 11. } Output:/p> 10 0 20 0 30 C++ Array Example: Traversal using foreach loop
  • 2. We can also traverse the array elements using foreach loop. It returns array element one by one. 1. #include <iostream> 2. using namespace std; 3. int main() 4. { 5. int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array 6. //traversing array 7. for (int i: arr) 8. { 9. cout<<i<<"n"; 10. } 11. } Output: 10 20 30 40 50 C++ Structs In C++, classes and structs are blueprints that are used to create instance of a class. Structs are used for lightweight objects such as Rectangle, color, Point etc. Unlike class, structs in C++ are value type than reference type. It is useful if you have data that is not intended to be modified after creation of struct. C++ Struct Example
  • 3. Let's see a simple example of struct Rectangle which has two data members widt h and height. 1. #include <iostream> 2. using namespace std; 3. struct Rectangle 4. { 5. int width, height; 6. 7. }; 8. int main(void) { 9. struct Rectangle rec; 10. rec.width=8; 11. rec.height=5; 12. cout<<"Area of Rectangle is: "<<(rec.width * rec.height)<<endl; 13. return 0; 14. } Output: Area of Rectangle is: 40 C++ Struct Example: Using Constructor and Method Let's see another example of struct where we are using constructor to initialize data and method to calculate area of rectangle. 1. #include <iostream> 2. using namespace std; 3. struct Rectangle 4. { 5. int width, height; 6. Rectangle(int w, int h) 7. { 8. width = w; 9. height = h; 10. }
  • 4. 11. void areaOfRectangle() { 12. cout<<"Area of Rectangle is: "<<(width*height); } 13. }; 14. int main(void) { 15. struct Rectangle rec=Rectangle(4,6); 16. rec.areaOfRectangle(); 17. return 0; 18. } Output: Area of Rectangle is: 24 C++ Pointers The pointer in C++ language is a variable, it is also known as locator or indicator that points to an address of a value. Advantage of pointer 1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions. 2) We can return multiple values from function using pointer. 3) It makes you able to access any memory location in the computer's memory. Usage of pointer There are many usage of pointers in C++ language.
  • 5. 1) Dynamic memory allocation In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used. 2) Arrays, Functions and Structures Pointers in c language are widely used in arrays, functions and structures. It reduces the code and improves the performance. Symbols used in pointer Symbol Name Description & (ampersand sign) Address operator Determine the address ∗ (asterisk sign) Indirection operator Access the value of an Declaring a pointer The pointer in C++ language can be declared using ∗ (asterisk symbol). 1. int ∗ a; //pointer to int 2. char ∗ c; //pointer to char Pointer Example Let's see the simple example of using pointers printing the address and value. 1. #include <iostream> 2. using namespace std; 3. int main() 4. { 5. int number=30; 6. int ∗ p; 7. p=&number;//stores the address of number variable 8. cout<<"Address of number variable is:"<<&number<<endl;
  • 6. 9. cout<<"Address of p variable is:"<<p<<endl; 10. cout<<"Value of p variable is:"<<*p<<endl; 11. return 0; 12. } Output Address of number variable is:0x7ffccc8724c4 Address of p variable is:0x7ffccc8724c4 Value of p variable is:30 Pointer Program to swap 2 numbers without using 3rd variable 1. #include <iostream> 2. using namespace std; 3. int main() 4. { 5. int a=20,b=10,∗p1=&a,∗p2=&b; 6. cout<<"Before swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl; 7. ∗p1=∗p1+∗p2; 8. ∗p2=∗p1-∗p2; 9. ∗p1=∗p1-∗p2; 10. cout<<"After swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl; 11. return 0; 12. } Output Before swap: ∗p1=20 ∗p2=10 After swap: ∗p1=10 ∗p2=20
  • 7. C++ Dynamic Memory A good understanding of how dynamic memory really works in C++ is essential to becoming a good C++ programmer. Memory in your C++ program is divided into two parts:  The stack: All variables declared inside the function will take up memory from the stack.  The heap: This is unused memory of the program and can be used to allocate the memory dynamically when program runs. Many times, you are not aware in advance how much memory you will need to store particular information in a defined variable and the size of required memory can be determined at run time. You can allocate memory at run time within the heap for the variable of a given type using a special operator in C++ which returns the address of the space allocated. This operator is called new operator. If you are not in need of dynamically allocated memory anymore, you can usedelete operator, which de-allocates memory previously allocated by new operator. The new and delete operators There is following generic syntax to use new operator to allocate memory dynamically for any data-type. new data-type; Here, data-type could be any built-in data type including an array or any user defined data types include class or structure. Let us start with built-in data types. For example we can define a pointer to type double and then request that the memory be allocated at execution time. We can do this using the newoperator with the following statements: double* pvalue = NULL; // Pointer initialized with null
  • 8. pvalue = new double; // Request memory for the variable The memory may not have been allocated successfully, if the free store had been used up. So it is good practice to check if new operator is returning NULL pointer and take appropriate action as below: double* pvalue = NULL; if( !(pvalue = new double )) { cout << "Error: out of memory." <<endl; exit(1); } delete pvalue; // Release memory pointed to by pvalue Let us put above concepts and form the following example to show how new and delete work: #include <iostream> using namespace std; int main () { double* pvalue = NULL; // Pointer initialized with null pvalue = new double; // Request memory for the variable *pvalue = 29494.99; // Store value at allocated address cout << "Value of pvalue : " << *pvalue << endl; delete pvalue; // free up the memory. return 0; } If we compile and run above code, this would produce the following result: Value of pvalue : 29495
  • 9. Dynamic Memory Allocation for Arrays Consider you want to allocate memory for an array of characters, i.e., string of 20 characters. Using the same syntax what we have used above we can allocate memory dynamically as shown below. char* pvalue = NULL; // Pointer initialized with null pvalue = new char[20]; // Request memory for the variable To remove the array that we have just created the statement would look like this: delete [] pvalue; // Delete array pointed to by pvalue Following is the syntax of new operator for a multi-dimensional array as follows: int ROW = 2; int COL = 3; double **pvalue = new double* [ROW]; // Allocate memory for rows // Now allocate memory for columns for(int i = 0; i < COL; i++) { pvalue[i] = new double[COL]; } The syntax to release the memory for multi-dimensional will be as follows: for(int i = 0; i < ROW; i++) { delete[] pvalue[i]; } delete [] pvalue; Dynamic Memory Allocation for Objects Objects are no different from simple data types. For example, consider the following code where we are going to use an array of objects to clarify the concept: #include <iostream>
  • 10. using namespace std; class Box { public: Box() { cout << "Constructor called!" <<endl; } ~Box() { cout << "Destructor called!" <<endl; } }; int main( ) { Box* myBoxArray = new Box[4]; delete [] myBoxArray; // Delete array return 0; } If you were to allocate an array of four Box objects, the Simple constructor would be called four times and similarly while deleting these objects, destructor will also be called same number of times. If we compile and run above code, this would produce the following result: Constructor called! Constructor called! Constructor called! Constructor called! Destructor called! Destructor called! Destructor called! Destructor called!