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!