SlideShare a Scribd company logo
1 of 168
Download to read offline
1.11. MATHEMATICS 181
24 return 0;
}
✌
✆
Output of above program is
✞
Addition of 5 and 2 is : 7
Subtraction of 5 and 2 is : 3
Multiplication of 5 and 2 is : 10
Division of 5 and 2 is : 2
Modulus of 5 and 2 is : 1
✌
✆
If mathematical expressions are mixed with C++ operators and are directly made to
be put at output stream then their grouping is required. Parentheses are used to group
the scope of expression.
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char ** argv ) {
5 /*3 + 3 << 1 *
* 6 << 1 *
7 * 6 1 */
/* Here << is considered as a *
9 *C++ insertion operator */
cout << 3 + 3 << 1 << endl ;
11 /*(3 + 3 << 1)*
* (6 << 1) *
13 * 12 */
/* Here << is considered as*
15 *a left shift operator */
cout << (3 + 3 << 1) << endl ;
17 return 0;
}
✌
✆
✞
61
12
✌
✆
182 Array & Pointer
2.1. ARRAY 183
2Array & Pointer
2.1 Array
Arrays in C++ stores data in a single variable name with an index, also known as a
subscript. It is simply a list or ordered grouping for variables of the same type. Arrays
often help a programmer in organize collections of data efficiently and intuitively.
2.1.1 Uni-dimensional Array
Arrays are declared and initialized like
✞
int numbers [6]; // array declared
2 int point [6]={0 , 0, 1, 0, 0, 0}; // array initialized
✌
✆
The brackets ‘[ ]’ identify ‘numbers’ or ‘points’ and the number enclosed in the bracket
indicates the number of elements in the array, i.e. subscripts of the array. An element
of array can be accessed by its index number. In following example, each element of the
array is accessed by its index number.
✞
#include <iostream >
2 using namespace std;
4 int main (int argc , char ** argv ) {
int ix;
6 short anArray [] = {3, 6, 9, 12, 15};
for (ix = 0; ix < ( sizeof (anArray ) / sizeof ( short)); ++ix) {
8 cout << anArray [ix] << endl ;
}
10 return 0;
}
✌
✆
In the above example, size of array was not explicitly specified. The compiler knows
size of array from the initialized list. The size of ‘anArray’ is ‘5’ because ‘anArray’ has
five elements. Addition of an additional element to the list will increase its size to six.
Static declaration of the size of an array, the array list will be overflow. To overcome this
problem sizeof expression is used as
✞
1 size = sizeof(anArray)/ sizeof(short)
✌
✆
Because of the sizeof expression in for loop, the script is automatically adjusted to this
change. Designated initializer is allow to pick and choose the initialized elements. An
array initialised with ‘[ ]’ is called expandable array. When an array is declared without
184 Array & Pointer
its size, compiler first counts elements of the array and then it grows the array upto a
size so that all the elements can be stored in the array.
✞
1 /* Array with growing size . */
int days [] = {31, 28, 31, 30, 31, 29};
✌
✆
A one dimensional array with variable size can not be declared as shown below:
✞
int i;
2 cin >> i;
int a[i]
✌
✆
The size must be constant. Again, if the array is created with variable size using new
keyword, then it is acceptable.
✞
1 #include <iostream >
using namespace std;
3
int main () {
5 int n, j;
cout << "How may array size : ";
7 cin >> n;
/* Reserve the memory */
9 int *a = new int[n];
for (j = 0; j < n; j++) {
11 a[j] = j*n;
}
13 for (j = 0; j < n; j++) {
cout << a[j] << endl ;
15 }
delete [] a;// Free the memory , required compulsory
17 return 0;
}
✌
✆
✞
0
3
6
✌
✆
2.1.2 Multi-dimensional Array
A multi-dimensional array can be declared and initialized as given below:
✞
1 int two_d [2][3] = {{ 5, 2, 1 },
{ 6, 7, 8 }};
✌
✆
Here [2] represents number of rows and [3] represents number of columns of the two
dimensional array. Multi-dimensional array can be used to add, subtract and product
(either dot or cross) of two vectors or matrices.
2.1. ARRAY 185
✞
#include <iostream >
2 using namespace std;
4 #define X 5
#define Y 5
6
int main (int argc , char ** argv ) {
8 int ix , iy;
10 short anArray[X][Y];
for (ix = 0; ix < X; ++ix) {
12 for (iy = 0; iy < Y; ++iy) {
anArray[ix][ iy] = ix * iy;
14 };
}
16 for (ix = 0; ix < X; ++ix) {
for (iy = 0; iy < Y; ++iy) {
18 cout << anArray [ix][iy] << "t";
};
20 cout << endl ;
}
22 return 0;
}
✌
✆
✞
0 0 0 0 0
0 1 2 3 4
0 2 4 6 8
0 3 6 9 12
0 4 8 12 16
✌
✆
Following is an example of elementwise addition and subtraction of two matrices.
✞
1 #include <iostream >
using namespace std;
3
/* Random number generator between 0 to 10.*/
5 int rand_num (int a, int b) {
return ((a * 97 + b * 21) & 10);
7 }
9 int main (int argc , char ** argv ) {
int i/* row*/,
11 j/* col*/;
int A [3][3]/* First Matrix*/,
13 B[3][3]/* Second Matrix*/ ,
C[3][3]/* Dot Matrix*/;
15 cout << "First Random Matrix is :" << endl ;
/* For each of three rows */
17 for (i = 0; i < 3; i++) {
/* There are three columns.*/
186 Array & Pointer
19 for (j = 0; j < 3; j++) {
/* Assign a random matrix elements .*/
21 A[i][j] = rand_num (i*j, j);
cout << A[i][j] << "t";
23 }
/* Print new line after completion of each row*/
25 cout << endl << endl ;
}
27 cout << "Second Random Matrix is :" << endl ;
/* For each of three rows */
29 for (i = 0; i < 3; i++) {
/* There are three columns.*/
31 for (j = 0; j < 3; j++) {
/* Assign a random matrix elements .*/
33 B[i][j] = rand_num (i, i * j);
cout << B[i][j] << "t";
35 }
/* Print new line after completion of each row*/
37 cout << endl << endl ;
}
39 cout << "Elementwise Addition of Matrices is :" << endl ;
/* For each of three rows */
41 for (i = 0; i < 3; i++) {
/* There are three columns.*/
43 for (j = 0; j < 3; j++) {
/* Add matrices elementwise .*/
45 C[i][j] = A[i][j] + B[i][j];
cout << C[i][j] << "t";
47 }
/* Print new line after completion of each row*/
49 cout << endl << endl ;
}
51 cout << "Elementwise Subtraction of Matrices is :" << endl ;
/* For each of three rows */
53 for (i = 0; i < 3; i++) {
/* There are three columns.*/
55 for (j = 0; j < 3; j++) {
/* Subtract matrices elementwise .*/
57 C[i][j] = A[i][j] - B[i][j];
cout << C[i][j] << "t";
59 }
/* Print new line after completion of each row*/
61 cout << endl << endl ;
}
63 return 0;
}
✌
✆
✞
First Random Matrix is :
0 0 10
0 2 8
0 2 10
2.1. ARRAY 187
Second Random Matrix is :
0 0 0
0 2 10
2 8 2
Elementwise Addition of Matrix is :
0 0 10
0 4 18
2 10 12
Elementwise Subtraction of Matrix is :
0 0 10
0 0 -2
-2 -6 8
✌
✆
Dot product example is
✞
#include <iostream >
2 using namespace std;
4 /* Random number generator between 0 to 10.*/
int rand_num (int a, int b) {
6 return ((a * 97 + b * 21) & 10);
}
8
int main (int argc , char ** argv ) {
10 int i/* row*/,
j/* col*/;
12 int A [3][3]/* First Matrix*/,
B[3][3]/* Second Matrix*/ ,
14 C[3][3]/* Dot Matrix*/;
cout << "First Random Matrix is :" << endl ;
16 /* For each of three rows */
for (i = 0; i < 3; i++) {
18 /* There are three columns.*/
for (j = 0; j < 3; j++) {
20 /* Assign a random matrix elements .*/
A[i][j] = rand_num (i*j, j);
22 cout << A[i][j] << "t";
}
24 /* Print new line after completion of each row*/
cout << endl << endl ;
26 }
cout << "Second Random Matrix is :" << endl ;
28 /* For each of three rows */
for (i = 0; i < 3; i++) {
30 /* There are three columns.*/
for (j = 0; j < 3; j++) {
32 /* Assign a random matrix elements .*/
B[i][j] = rand_num (i, i * j);
34 cout << B[i][j] << "t";
}
36 /* Print new line after completion of each row*/
cout << endl << endl ;
188 Array & Pointer
38 }
cout << "Dot Product of Matrices is :" << endl ;
40 /* For each of three rows */
for (i = 0; i < 3; i++) {
42 /* There are three columns.*/
for (j = 0; j < 3; j++) {
44 /* Subtract matrices elementwise .*/
C[i][j] = A[i][j] * B[i][j];
46 cout << C[i][j] << "t";
}
48 /* Print new line after completion of each row*/
cout << endl << endl ;
50 }
return 0;
52 }
✌
✆
✞
First Random Matrix is :
8 2 2
2 2 0
2 0 8
Second Random Matrix is :
8 8 8
8 2 2
8 2 8
Dot Product Matrix is :
64 16 16
16 4 0
16 0 64
✌
✆
Cross product example is
✞
#include <iostream >
2 #include <cmath >
using namespace std;
4
/* Random number generator between 0 to 10.*/
6 int newseed = 10;
8 int seed (int a) {
newseed = newseed + a;
10 return newseed;
}
12
int rand_num (int a) {
14 seed (a);
return (( newseed * 99991 + 12345) & 10);
16 }
18 int main (int argc , char ** argv ) {
int i/* row*/,
20 j/* col*/;
2.1. ARRAY 189
int A[3]/* First Matrix */,
22 B[3]/* Second Matrix*/,
C[3]/* Vector Matrix*/;
24 cout << "First Random Matrix is :" << endl ;
/* For each of three rows */
26 for (i = 0; i < 3; i++) {
/* There are three columns.*/
28 /* Assign a random matrix elements .*/
A[i] = rand_num (i);
30 cout << A[i] << "t";
}
32 cout << endl ;
cout << "Second Random Matrix is :" << endl ;
34 /* For each of three rows */
for (i = 0; i < 3; i++) {
36 /* There are three columns.*/
/* Assign a random matrix elements .*/
38 B[i] = rand_num (i);
cout << B[i] << "t";
40 }
cout << endl ;
42
cout << "Cross Product of Matrices is :" << endl ;
44 /* For each of three rows */
for (i = 0; i < 3; i++) {
46 /* Subtract matrices elementwise .*/
C[i] = pow(-1, 2 * i)* (A[(i + 1) % 3] * B[(i + 2) % 3] 
48 - B[(i + 1) % 3] * A[(i + 2) % 3]);
cout << C[i] << "t";
50 }
return 0;
52 }
✌
✆
✞
First Random Vector is :
10 2 0
Second Random Vector is :
0 10 8
Cross Product Vector is :
16 -80 100
✌
✆
Array can be passed to a function like
✞
#include <iostream >
2 using namespace std;
4 /*+- Array pointer with **
**| expandable size */
6 void init_array (int a[], int count) {
int i;
8 for (i = 0; i < count; i++)
a[i] = i * 10;
190 Array & Pointer
10 for (i = 0; i < count; i++)
cout << "The a value is " << a[i] << endl ;
12 }
14 int main (int argc , char ** argv ) {
int mydata [10];
16 init_array (mydata , 5);
return 0;
18 }
✌
✆
✞
The a value is 0.
The a value is 10.
The a value is 20.
The a value is 30.
The a value is 40.
✌
✆
For multidimensional array, there is no limit of dimension in C. Here, a four dimensional
matrix is represented by
✞
1 int myData [2][3][2][4]
✌
✆
A new dimension in array declaration is always grouped by curly braces. One dimensional
array has one curly braces, i.e. one row. In two dimensional array, there are two one
dimensional rows both separated by comma (,) operator. These two rows are enclosed by
another curly braces. In three dimensional systems of arrays, two 2-dimensional arrays
are placed one over another. In the following example, two, three and four dimensional
arrays are declared.
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char ** argv ) {
5 int a [2][2] = {
// cols
7 {1, 2}, // row
{5, 6} // row
9 };
int b [2][2][2] = {
11 {
// cols
13 {1, 2}, // row
{5, 6} // row
15 },
{// height
17 {4, 3},
{8, 9}
19 }
};
21 int c [2][2][2][2] = {
{
2.1. ARRAY 191
23 {
// cols
25 {1, 2}, // row
{5, 6} // row
27 },
{// height
29 {1, 2},
{5, 6}
31 }
},
33 {// time
{
35 {4, 1},
{7, 6}
37 },
{
39 {4, 4},
{9, 1}
41 }
}
43 };
int i, j, k, l;
45 cout << "Elements of matrix a are " << endl ;
for (i = 0; i < 2; i++) {
47 for (j = 0; j < 2; j++) {
cout << "Element " << a[i][j] << endl ;
49 }
}
51 cout << "Elements of matrix b are " << endl ;
for (i = 0; i < 2; i++) {
53 for (j = 0; j < 2; j++) {
for (k = 0; k < 2; k++) {
55 cout << "Element " << b[i][j][k] << endl ;
}
57 }
}
59 cout << "Elements of matrix c are " << endl ;
for (i = 0; i < 2; i++) {
61 for (j = 0; j < 2; j++) {
for (k = 0; k < 2; k++) {
63 for (l = 0; l < 2; l++) {
cout << "Element " << c[i][j][k][l] << endl ;
65 }
}
67 }
}
69 return 0;
}
✌
✆
192 Array & Pointer
2.1.3 Array in Function
In a function, an argument is passed as value unless the program needs to alter the
argument. In this case there is requirement that a pointer should be passed to the
function. Arrays can passed to a function as pointers. If an array is passed to the
function, function would have to allocate enough space to hold a copy of the original
array and then copy all the data from the original array to the new array. It is much
quicker to pass the address of the array rather than array itself and have the function
work with the original data. Prototype for the passing of an array to the function is
✞
int sum(int arr [])
✌
✆
C++ compilers do not check the size of the array passed to the function hence for good
programming, the function should know the limits of actions on the array. This is why a
new parameter of array size as ‘n’ is passed to the function as
✞
1 int sum(int arr[], int n)
✌
✆
The name of an array is address of first element hence array name passed as argument to
the function should be matching argument and a pointer. In this context int arr[] is same
as the int * arr. In case of multi-dimensional array, first bracket in the multidimensional
array may be empty or not empty but other bracket should contains a valid integer for
the size of the array dimension.
✞
1 #include <iostream >
using namespace std;
3 #define ROWS 3
#define COLS 4
5 int sum(int rows , int cols , int ar [][ COLS ]);
7 int main (void ) {
int i, j;
9 int varr [ROWS ][ COLS ];
for (i = 0; i < ROWS ; i++)
11 for (j = 0; j < COLS ; j++)
varr [i][j] = i * j + j;
13 cout << "3x4 Array n";
cout << "Sum of all elements " << sum(ROWS , COLS , varr );
15 return 0;
}
17
int sum(int rows , int cols , int ar [][ COLS ]) {
19 int r;
int c;
21 int tot = 0;
for (r = 0; r < rows ; r++)
23 for (c = 0; c < cols ; c++)
tot += ar[r][c];
25 return tot;
}
✌
✆
2.1. ARRAY 193
✞
3x4 Array
Sum of all elements 36
✌
✆
2.1.4 Return Array From Function
C++ allows to return an array from a function. To return single dimension array, we
create a function with pointer. See the example below:
✞
#include <iostream >
2 #include <ctime >
using namespace std;
4
int * getArray () {
6 static int a[5];
8 for (int i = 0; i < 5; ++i) {
a[i] = i * 2;
10 }
return a;
12 }
14 int main (int argc , char *argv []) {
int *p;
16
p = getArray ();
18
for (int i = 0; i < 5; i++) {
20 cout << "*(p + " << i << ") : ";
cout << *(p + i) << endl ;
22 }
24 return 0;
}
✌
✆
✞
*(p + 0) : 0
*(p + 1) : 2
*(p + 2) : 4
*(p + 3) : 6
*(p + 4) : 8
✌
✆
2.1.5 String As Array
String is defined as array of characters. C++ allows a character array to be represented
by a character string with a null terminating character which is automatically added at
the end of character array instead of a list of characters. Example of string array is shown
below.
194 Array & Pointer
✞
1 char string [] = {’A’, ’p’, ’p’, ’l’, ’e’, ’S’, ’0 ’};
✌
✆
Normal size of a string array is controlled at initialization of the string array. An string
array stores elements upto its declared length. Excess elements are ignored and skipped.
In following example only ten characters will be stored in the string array ‘mystr’.
✞
1 char mystr [10] = "Apple is red.";
✌
✆
It is convenient to let the compiler determine the array size. If anyone omits the size of
array at the time of array declaration and initialization, the compiler itself determines the
size for supplied string. In following example, compiler set the string length of thirteen
characters.
✞
1 char mystr[] = "Apple is red.";
✌
✆
A pointer-to-string method may also be used for string declaration and initialization. In
pointer notation, above example will be looked like
✞
1 const char *ptrstr = "Merkkijono ";
✌
✆
Both declarations amount to saying that ‘ptrstr’ is a pointer to the indicated string.
‘ptrstr’ string variable declared as array or as pointer, both are same but only pointer
version can be used with increment operator. To create an extra long string, string is
splitted into multiple sections, by closing the first section with a quote, and recommencing
the string on the next line (also starting and ending in a quote):
✞
1 char string [] = "This is a very , very long "
"string that requires two lines.";
✌
✆
Full example is given below:
✞
#include <iostream >
2 using namespace std;
4 int main (int argc , char *argv []) {
char ch;
6 char string[] = "Two lines "
"string.";
8 int i = 0;
while (string[i] != ’0’) {
10 ch = string[i];
cout << ch;
12 i++;
}
14 return 0;
}
✌
✆
✞
T.w.o. .l.i.n.e.s. .s.t.r.i.n.g...
✌
✆
2.1. ARRAY 195
When an array is declared and initialized with characters, there must be a terminating
null character. Otherwise there shall be garbage output. For example following syntax
has no terminating null character. It is not in standard format.
✞
1 char a[10];
a[0]= ’a’;
3 a[1]= ’r’;
a[2]= ’u’;
✌
✆
In above method, a null terminator is added as its last element. Now, the string array is
initialized in standard format.
✞
char a[10];
2 a[0]= ’a’;
a[1]= ’r’;
4 a[2]= ’u’;
a[3]= ’0’;
✌
✆
See following two examples, in which string is terminating without and with null termi-
nating character. First example gives garbage output (see below).
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char *argv []) {
5 char a[10];
a[0] = ’a’;
7 a[1] = ’r’;
a[2] = ’u’;
9 cout << a;
return 0;
11 }
✌
✆
✞
<garbage output >
✌
✆
In this second example, string is terminated with null character. This example gives
output what we required.
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char *argv []) {
5 char a[10];
a[0] = ’a’;
7 a[1] = ’r’;
a[2] = ’u’;
9 a[3] = ’0’;
cout << a;
11 return 0;
}
✌
✆
196 Array & Pointer
✞
aru
✌
✆
Static array size should be larger than one to the required size of the array to store data.
For example, to store one byte data, array size should be two. Similarly, for storing n
bytes data, array size should be at least n + 1.
2.1.6 Size of Array
C++ features two kinds of arrays: static (compile-time, fixed size) and dynamic (allocated
at run-time). The length of a dynamic array cannot be acquired from the array itself -
its length must be stored elsewhere. The size of array is computed as
✞
1 int length = sizeof(<array name >) / sizeof(<array element >);
✌
✆
Preprocessor ways for array length is defined as
✞
1 #define ARRAY_LENGTH (A) (sizeof(A) / sizeof(A[0]) )
✌
✆
Arrays become pointers when passed as a parameter to a function. Thus, the length of
an array parameter may not require directly. A dedicated length parameter is required.
An example is given below.
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char *argv []) {
5 const char *fruit[2] = {"apples", "oranges"};
7 /* Length of the array by dividing *
*the size of all elements by the*
9 *size of the first element. */
11 int length = sizeof (fruit) / sizeof (fruit[0]) ;
13 cout << length;
15 return 0;
}
✌
✆
✞
2
✌
✆
In above example, length of the array is obtained by dividing the size of all elements
(found with sizeof (fruit)) by the size of the first element. Note that since the array
elements are pointers to null-terminated character arrays, the size of the first element is
actually the size of the pointer type - not the length of the string. This size, regardless
of the type being pointed to, is 8 bytes, 4 bytes, or 2 bytes on 64-bit, 32-bit, or 16-bit
platforms respectively. Pointer can be used for variable size array as shown in example
below.
2.2. POINTER 197
✞
1 #include <iostream >
using namespace std;
3 /* Variable size array.*/
char *name ;
5
int main (int argc , char *argv []) {
7 name = "My School!!";
int i = 0;
9 while (name [i] != ’0’) {
cout << name [i] << endl ;
11 i++;
}
13 return 0;
}
✌
✆
✞
M
y
S
c
h
o
o
l
!
!
✌
✆
2.2 Pointer
A pointer is a simple variable that stores address (the location in memory) of a value
in memory rather than storing data itself. There are four fundamental things for the
pointers:
1. How to declare them.
2. How to assign them.
3. How to reference the value to which the pointer points, i.e value finding also known
as dereferencing.
4. How they relate to arrays.
Two important rules of the pointer must be remembered. These are:
1. A variable name with prefixed by ampersand (&) defines the address of the variable
and therefore points to the variable.
2. A pointer with prefixed by asterisk (*) refers to the value of the variable pointed-by
the pointer.
198 Array & Pointer
An array name is also an address of the first element of the array. Assume, ‘arr’ is an
array as relation geven below:
✞
arr == &arr [0];
✌
✆
Here both ‘arr’ and ‘&arr[0]’ represent to the memory address of first element of the same
array. A pointer can points to any element of an array, if the pointer is assigned address of
that element. In the following example, pointer ‘x’ points to the address of first element
of tha array ‘i’.
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char *argv []) {
5 int i[5] = {10, 20, 30, 40, 50};
int *x = &i[0]; /* Points to first element.*/
7 cout << *x;
return 0;
9 }
✌
✆
0
10
1
20
2
30
3
40
4
50
i[]:
x
The output of above program shall be
✞
10
✌
✆
If above example is modified as given below, then the pointer ‘x’ points to the 3rd
element of the array ‘i’.
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char *argv []) {
5 int i[5] = {10, 20, 30, 40, 50};
int *x = &i[2]; /* Points to third element.*/
7 cout << *x;
return 0;
9 }
✌
✆
0
10
1
20
2
30
3
40
4
50
i[]:
x
2.2. POINTER 199
The output of above program shall be
✞
30
✌
✆
If an intger is pointed by a pointer-to-char variable, then this variable can points to
the address of each byte of the integer variable (integer variable is 4 bytes long).
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char *argv []) {
5 /* 1000 D = 1111101001 B*/
int i = 1001;
7 /* Pointer casting from integer to character .*/
char *x = (char *) &i;
9 /* Little endian is x[0]=11101001 B*
*Big endian is x[1]=00000011 B*
11 *Big endian x[2]= x[3]=00000000 B*/
/* Print little endian x[0]*/
13 cout << (int) x[0] << endl ;
return 0;
15 }
✌
✆
x[3] x[2] x[1] x[0]
i:
x
00000000 00000000 00000011 11101001
Output of above program is
✞
-23
✌
✆
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char *argv []) {
5 /* 1000 D = 1111101001 B*/
int i = 1001;
7 /* Pointer casting from integer to character .*/
char *x = (char *) &i;
9 /* Little endian is x[0]=11101001 B*
*Big endian is x[1]=00000011 B*
11 *Big endian x[2]= x[3]=00000000 B*/
/* Print big endian x[1]*/
13 cout << (int) x[1] << endl ;
return 0;
15 }
✌
✆
200 Array & Pointer
x[3] x[2] x[1] x[0]
i:
x
00000000 00000000 00000011 11101001
Output of above program is
✞
3
✌
✆
2.2.1 Declaring Pointers
In C, pointers are declared as shown in following syntax.
✞
1 long *var1 , var2 ;
int **p3;
✌
✆
In these syntax, line 1 declares ‘var1’ as a pointer to a long and ‘var2’ as a long and not
a pointer to a long. In line 2, ‘p3’ is declared as a pointer to a pointer to an int. In C++,
a pointer is declared as shown in the following syntax.
✞
int * A;
2 int * ptrA , ptrB ;
✌
✆
Here ‘A’, ‘ptrA’ are pionter to integer while ‘ptrB’ is an ordinary integer. See an example
given below:
✞
#include <iostream >
2 using namespace std;
4 int main (int argc , char ** argv ) {
int i;
6 int* p, j;
p = &i; /* valid for best practice */
8 i = 10; /*i is now 10 */
*p = 20; /* valid*/
10 j = 5;
/* prints 20*/
12 cout << "i is " << i << endl ;
cout << "i is " << *p << endl ;
14 /* prints 5*/
cout << "j is " << j << endl ;
16 return 0;
}
✌
✆
✞
i is 20
i is 20
j is 5
✌
✆
2.2. POINTER 201
1
0x49
2
0x50
3
0x51
4
0x52
5
0x53
6
0x54
7
0x55
int *p = &i
i
&i
Pointer types are often used as parameters to function calls.
✞
1 int MyFunction ( struct MyStruct *pStruct );
✌
✆
In the above syntax, it is explained that how to declare a function which uses a pointer as
an argument. Since C++ passes function arguments by value, in order to allow a function
to modify a value from the calling routine, a pointer to the value must be passed. Pointer-
to-Structure is also used as function arguments even when nothing in the struct will be
modified in the function. This is done to avoid copying the complete contents of the
structure onto the stack. A simple example is
✞
1 #include <iostream >
/* time .h C library in C++ header as ctime*/
3 #include <ctime >
using namespace std;
5
void getSeconds (unsigned long *par);
7
int main (int argc , char ** argv []) {
9 unsigned long sec;
getSeconds (& sec);
11 cout << "Number of seconds since 01 Jan 1970 : " << sec;
return 0;
13 }
15 void getSeconds (unsigned long *par) {
*par = time (NULL );
17 return;
}
✌
✆
✞
Number of seconds: 1420616845
✌
✆
2.2.2 Pointer to Member
A member of a structure or class or a namespace are also accessible via pointers. A pointer
to member shall not point to a static member of a class, i.e. a member with reference
type. “pointer to member” is distinct from the type “pointer”, therefore, a pointer to
member is declared only by the pointer to member declarator syntax, and never by the
pointer declarator syntax.
✞
1 int X::* i = &X::a; // pointer to member method
int *i = &a; // pointer declarator method
✌
✆
202 Array & Pointer
See the example below:
✞
#include <cstdlib >
2 #include <iostream >
using namespace std;
4
struct X {
6 int a;
};
8
int main (int argc , char ** argv ) {
10 /* Declare member function i as pointer *
*to the original member a of the struct*/
12 int X::* i = &X::a;
X x;
14 x.*i = 10;
cout << x.*i;
16 return 0;
}
✌
✆
✞
10
✌
✆
2.2.3 Pointer Address
Pointers are used to point the memory address where data is stored. A pointer size is
determined by the pointer data type. For example if pointer is character type then size
of pointer is one byte. The pointer increment is one byte long. For example,
✞
1 string *ptr= new string [8];
✌
✆
and pointer ‘ptr’ points to memory address 0×00 then ‘ptr++’ points to the memory
address 0×01 as shown in the following figure.
d
0x00
e
0x01
f
0x02
g
0x03
h
0x04
i
0x05
j
0x06
k
0x07
Bytes
ptr ptr++
*ptr (*ptr)++
Again ‘*ptr’ points to the character ‘d’ at the memory address pointed by the pointer
‘ptr’. To get the next character ‘e’, dereference is done as ‘(*ptr)++’. Similarly, if pointer
is integer type as declared below:
✞
1 int *ptr= new int [10];
✌
✆
2.2. POINTER 203
then size of ‘ptr’ is 4 bytes. Now, if pointer ‘prt’ points to the memory address 0×00 then
‘ptr++’ points to the memory address 0×04 as shown in the figure given below:
xxxx
0x00
xxxx
0x01
xxxx
0x02
xxxx
0x03
yyyy
0x04
yyyy
0x05
yyyy
0x06
yyyy
0x07
Bytes
ptr ptr++
*ptr (*ptr)++
Again ‘*ptr’ points to the integer value at the memory address pointed by the pointer
‘ptr’. To get the next integer value, dereference is done as ‘(*ptr)++’. Remember that
precedence of ‘++’ symbol is higher to asterisk (*) symbol. This is why to scope of
asterisk (*) is changed by using parenthesis.
2.2.4 Assigning Values to Pointers
To assign address of a variable to a pointer, unary operator ‘&’, also known as ‘address
of’ operator is used as shown in the following syntax.
✞
1 /*An interger variable that have *
*null value stored in memory. */
3 int myInt;
/* Pointer that addresses to an integer value.*/
5 int * ptr;
/* Address to the pointer where *
7 *myInt value is stores in memory.*/
ptr = &myInt;
✌
✆
Here, ‘ptr’ is referencing to ‘myInt’ now. Pointers can also be assign the address of
dynamically allocated memory. See the following example.
✞
#include <iostream >
2 using namespace std;
4 int j, k;
int * ptr;
6
int main (int argc , char ** argv ) {
8 j = 1;
k = 2;
10 ptr = &k;
cout << "j = " << j << ". It stored at " << (void *) &j << endl ;
12 cout << "k = " << k << ". It stored at " << (void *) &k << endl ;
cout << "‘ptr’ = " << ptr << ". It stored at "
14 << (void *) &ptr << endl ;
cout << "Value of the integer pointed -by ‘ptr’ is " << *ptr <<
endl ;
16 return 0;
204 Array & Pointer
}
✌
✆
✞
j has value 1 and stored at 0x403100
k has value 2 and stored at 0x403120
‘ptr ’ has value 0x403120 and stored at 0x403110
Value of the integer pointed -by ‘ptr ’ is 2
✌
✆
Assigning a value to a pointer requires specialization. In C++, it is best practice that
first assign the address of a value to the pointer. We can retrieve the value from the
address by dereferencing it using asterisk (‘*’);
✞
int * j;
2 int k = 5;
j = &k/* Valid & good practice .*/
✌
✆
See the example
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char ** argv ) {
5 int * j;
int k = 15;
7 j = &k; /* valid & good practice */
cout << "j is : " << *j;
9 return 0;
}
✌
✆
✞
j is : 15
✌
✆
Assigning a value to a pointer directly causes errors in the C++ program. Therefore, it
is not assumed a good practice. Sometimes, confusion creates a bad way for assignment
of a value to a pointer as shown below:
✞
1 int * j;
*j = 5;/* Invalid & very bad practice .*/
✌
✆
It is as we try to assign a value to an uninitialized pointer. A pointer points to the
location (address) where value is stored. Pointer does not store value itself. So, pointer
does not know where value is stored. If we try to do so, the program either may crash or
it damaged to the system.
✞
#include <iostream >
2 using namespace std;
4 int main (int argc , char ** argv ) {
int i;
6 int *p;
p = &i; /* valid for best practice */
2.2. POINTER 205
8 i = 10; /*i is now 10 */
*p = 20; /* valid*/
10 /* prints 20*/
cout << "i is " << i << endl ;
12 cout << "i is " << *p << endl ;
return 0;
14 }
✌
✆
✞
i is 20
i is 20
✌
✆
When we create a pointer in C++, the computer allocates memory to hold an address,
but it does not allocate memory to hold the data to which the address points. Space for
data is created by another step. If we omit the step required to create space for data
attracts the errors.
✞
int * i;
2 *i = 10;
✌
✆
Here, i is a pointer but it point to nothing. Therefore, code failed to assign an address to
i. See the example below, which will failed to give desired output.
✞
#include <iostream >
2 using namespace std;
4 int main (int argc , char ** argv ) {
int* p;
6 *p = 5;
cout << "p is " << *p << endl ;
8 return 0;
}
✌
✆
In C++, memory for pointer is allocated by new operator. To allocate memory for integer
we use the syntax like
✞
1 int * j = new int;
✌
✆
We tell to operator new for what data type we want in memory. It finds a block of the
correct size and returns the address of the block. A practical example is given below:
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char ** argv ) {
5 int *j = new int;
*j = 5; /* valid & good practice */
7 cout << "j is : " << *j;
return 0;
9 }
✌
✆
206 Array & Pointer
✞
j is : 5
✌
✆
Each allocated memory by new operator only should be freed by delete operator. It is
used as
✞
1 int *j = new int;/* Create & reserve memory space*/
delete j; /* Free memory space*/
✌
✆
The use of delete operator as given below is illegal.
✞
int i = 5;
2 int *j = &i;
delete j; /* illegal */
✌
✆
2.2.5 Pointer Dereferencing (Value Finding)
To access a value to which a pointer points, the asterisk (‘*’) operator is used. An-
other operator, the ‘−>’ (Indirection) operator is used in conjunction with pointers to
structures. Here’s a short example.
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char ** argv ) {
5 int i;
int *p; // Pointer type int *
7 p = &i; // p now points to i
i = 10; // i is now 10
9 *p = 20; // i is now 20!!
/* prints "20" */
11 cout << "i is " << i << endl ;
/* "20"! dereferencing -p is the same as i!*/
13 cout << "i is " << *p << endl ;
return 0;
15 }
✌
✆
✞
i is 20
i is 20
✌
✆
2.2.6 Addition of Pointers
A pointer when dereferences, retrieves the value at the address pointed by the pointer.
If the value at pointer address is an integer then we can add another integer value to it.
When an integer value is addedd to the pointer then old addres of the pointer is changed
into new address. Difference between new address and old address is equal to the pointer
data type. In the following example, we retrieve the pointer value and add 1 to in function
‘increment()’.
2.2. POINTER 207
✞
#include <iostream >
2 using namespace std;
4 void increment (int *p) {
*p = *p + 1; /* Add one to p */
6 }
8 int main (int argc , char ** argv ) {
int i = 20;
10 /* i value is 20 */
cout << "i is " << i << endl ;
12 /* Pass interger to increment function as pointer */
increment (&i);
14 /* Print the value 21*/
cout << "i is " << i << endl ;
16 return 0;
}
✌
✆
✞
i is 20
i is 21
✌
✆
The value of a pointer is the address of the object to which it points. The address of a
large object, such as type double variable, typically is the address of the first byte of the
object. Applying the * operator to a pointer yields the value stored in the pointed-to
object. Adding 1 to the pointer increases its value by the size, in bytes, of the pointed-to
type.
2.2.7 Pointers and Arrays
If we have to use pointer for an array, then we use new operator to create a dynamic
array of specific size. The valid types of dynamic allocation of array memory space are
shown below:
✞
int * i = new int [10];/* 40 bytes space for 10 elements */
2 string * str = new string [10];/*10 bytes string.*/
✌
✆
new operator returns the address of the first element of the block. We should free the
allocated memory space by delete operator when program does not need it. Single block
of memory should be created and freed like
✞
int * i = new int; /* Single byte memory space*/
2 delete i; /* Free the allocated memory space*/
✌
✆
A dynamic array memory space should be created and freed like
✞
int * i = new int [10]; /*10 block memory */
2 delete [] i; /* Free memory allocated for array*/
✌
✆
208 Array & Pointer
Here ‘[]’ between delete operator and variable ‘i’ tells the program that it should free the
whole array, not just the element pointed to by the pointer.
✞
#include <iostream >
2 using namespace std;
4 int main (int argc , char ** argv ) {
int * mk = new int [10];
6 *mk = 65874859;
cout << *mk << endl ;
8 delete [] mk;
return 0;
10 }
✌
✆
✞
65874859
✌
✆
To add a value to a pointer we can use ‘*’ (asterisk) operator as well as array element
method to the dynamically allocated array as shown in following example.
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char ** argv ) {
5 int * mk = new int [5];
int i;
7 for (i = 0; i < 5; i++) {
mk[i] = i;
9 }
for (i = 0; i < 5; i++) {
11 cout << mk[i] << endl ;
}
13 delete [] mk;
return 0;
15 }
✌
✆
✞
0
1
2
3
4
✌
✆
If we want to add and retrieve values to dynamically allocated memory by using pointer
then initial pointer location must be restored to get the actual stored values. See the
example below:
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char ** argv ) {
5 int * mk = new int [5];
2.2. POINTER 209
int i;
7 for (i = 0; i < 5; i++) {
*mk = i; // assign value at pointer location
9 mk ++; // increase pointer location by one
}
11 mk = mk -5; // Restore the initial position of the pointer.
for (i = 0; i < 5; i++) {
13 cout << *mk << endl ;
mk ++;
15 }
delete [] mk;
17 return 0;
}
✌
✆
✞
0
1
2
3
4
✌
✆
Pointer arithmetic can be used to increment the pointer position and retrieval of the value
stored at that address.
✞
1 #include <iostream >
#include <string >
3 using namespace std;
5 int main (int argc , char ** argv ) {
int * mk = new int [5];
7 int i;
for (i = 0; i < 5; i++) {
9 mk[i] = i;
}
11 for (i = 0; i < 5; i++) {
cout << *(mk + i) << "t" << (mk [0] + i) << endl ;
13 }
delete [] mk;
15 return 0;
}
✌
✆
✞
0 0
1 1
2 2
3 3
4 4
✌
✆
Pointers to Arrays
An array can be initialized by using any of the following methods:
210 Array & Pointer
✞
1 int myArr [3] = {a, b, c};
int * arrPtr = myArr; /* name of an array = address */
3 int * arrPtr = &myArr[0]; /*or use address operator */
✌
✆
First line in above syntax is initialization of an array. In second line, ‘arrPtr’ is a pointer
to the array ‘myArr’. In third line, ‘arrPtr’ points to the address of first element of the
array ‘myArr’. See the following example, in which both methods are used to assign the
same array to two different pointers by two different methods.
✞
1 #include <iostream >
#include <string >
3 using namespace std;
5 int main (int argc , char ** argv ) {
double Marks[3] = {120.0 , 200.0 , 150.0};
7 /* Here are two ways to get the address of an array*/
double * p1 = Marks; /* name of an array = address */
9 double * p2 = &Marks [0]; /*or use address operator */
// with array element
11 cout << "p1 = " << p1 << ", *p1 = " << *p1 << endl ;
cout << "p2 = " << p2 << ", *p2 = " << *p2 << endl ;
13 p1 = p1 + 1;
p2 = p2 + 1;
15 cout << "Add 1 to the p1 & p2 pointers : n";
cout << "p1 = " << p1 << ", *p1 = " << *p1 << endl ;
17 cout << "p2 = " << p2 << ", *p2 = " << *p2 << endl ;
p1 = p1 + 1;
19 p2 = p2 + 1;
cout << "Add 1 to the p1 & p2 pointers : n";
21 cout << "p1 = " << p1 << ", *p1 = " << *p1 << endl ;
cout << "p2 = " << p2 << ", *p2 = " << *p2 << endl ;
23 return 0;
}
✌
✆
✞
p1 = 0x22 ff40, *p1 = 120
p2 = 0x22 ff40, *p2 = 120
Add 1 to the p1 & p2 pointers :
p1 = 0x22 ff48, *p1 = 200
p2 = 0x22 ff48, *p2 = 200
Add 1 to the p1 & p2 pointers :
p1 = 0x22 ff50, *p1 = 150
p2 = 0x22 ff50, *p2 = 150
✌
✆
Pointers as Function Argument
Pointers can also be used as function arguments in C++. Function prototype with pointer
argument is shown below:
✞
int myFunc(int* a);
✌
✆
2.2. POINTER 211
When we call this function, we use ‘&’ (address of) symbol to pass the address of a
variable not the value of the variable as function argument. The function is called like
✞
1 int i=10; // variable i with assigned value 10
myFunc(&i); // pass address of i to function myFunc
✌
✆
By this way, pointer ‘a’ is assigned the address of the function parameter ‘i’. In following
example, a sum function takes two integer values as pointer and return their sum as
integer. The call of sum function uses addresses of the two integer values by using address-
of symbol (‘&’).
✞
#include <iostream >
2 using namespace std;
4 /*pass -by -value as pointers to a & b to sum()*/
int sum(int* a, int* b) {
6 int f;
/* Passed values as a and b.*
8 *They can be changed here .*/
f = *a + *b;
10 return f;
}
12
int main (int argc , char *argv []) {
14 int i = 2, j = 3, g;
/* Pass address of i and j to sum *
16 *function not values of i and j */
g = sum (&i, &j);
18 cout << "Sum of " << 2 << ", " << 3 << " is " << g;
return 0;
20 }
✌
✆
✞
Sum of 2, 3 is 5
✌
✆
00000010 00000011
0xaa 0xbb
i j
g = sum(&i, &j);
212 Array & Pointer
00000010 00000011
0xaa 0xbb
i j
int sum(int* a, int* b) {}
A pointer function can also be used as function argument, generally called function
callback. See the example
✞
1 #include <iostream >
using namespace std;
3
int getSum(int i, int j, int (* PrintLabel )(int , int)) {
5 cout << "Sum of " << i << " and " << j << " is ";
cout << PrintLabel (i, j);
7 }
9 int PrintLabel (int x, int y) {
return (x + y);
11 }
13 int main (int argc , char *argv []) {
15 getSum (2, 4, PrintLabel );
return 0;
17 }
✌
✆
✞
Sum of 2 and 4 is 6
✌
✆
Address as Function Argument
Address of can also be used as function argument in C++. Function prototype with
address of argument is as:
✞
1 int myFunc(int& a);
✌
✆
Here, int& passes a reference to the function. When we call this function, we just pass
the variables as argument. The function call should be like
✞
1 int i=10;
myFunc(i);
✌
✆
In following example, a sum function takes addresses of two arguments and return their
sum as integer. The function call of this sum function uses variables as function argu-
ments.
2.2. POINTER 213
✞
#include <iostream >
2 using namespace std;
4 /*pass -by -value as address of a & b to sum()*/
int sum(int& a, int& b) {
6 int f;
/* Passed values as a and b.*
8 *They can be changed here .*/
f = a + b;
10 return f;
}
12
int main (int argc , char *argv []) {
14 int i = 2, j = 3, g;
/* Sum function with arguments i and j*/
16 g = sum(i, j);
cout << "Sum of " << 2 << ", " << 3 << " is " << g;
18 return 0;
}
✌
✆
✞
Sum of 2, 3 is 5
✌
✆
2.2.8 Constant Pointers
A pointer may be declared as constant by using const keyword.
✞
1 int i = 5;
const int *p = &i;
3 //Or
int const *p = &i;
✌
✆
There are two cases, (i) where a pointer pointed to constant data (pointee) and pointee
can not be changed, and (b) where constant pointer (address) can not be changed. The
usual pointer-pointee relation are given below:
✞
#include <iostream >
2 using namespace std;
4 int main () {
int i = 2;
6 int j = 3;
int *k = &j; // k points to j and *k is 3
8 cout << *k << endl ;
j = 6; // Now both j and *k are 6
10 cout << j << " " << *k << endl ;
*k = 7; // j and *k are 7. Pointee changes
12 cout << j << " " << *k << endl ;
k = &i; // k points to i. *k is 2. Pointer changes
14 cout << i << " " << *k << endl ;
214 Array & Pointer
*k = 8; // i and *k are 8 now. Pointee changes
16 cout << i << " " << *k << endl ;
return 0;
18 }
✌
✆
✞
3
6 6
7 7
2 2
8 8
✌
✆
Now the const keyword is used as shown in modified example. There are errors shows by
the compiler.
✞
1 #include <iostream >
using namespace std;
3
int main () {
5 int i = 2;
const int j = 3;
7 const int *k = &j;
j = 6; // Error! assignment of read -only variable ’j’
9 *k = 7; // Error! assignment of read -only location ’* k’
k = &i; // k points to i. *k is 2. Pointer changes
11 *k = 8; // Error! assignment of read -only location ’* k’
return 0;
13 }
✌
✆
Here, code line
✞
1 //+--Pointee type , i.e. constant pointee
//|
3 const int *k = &j;
✌
✆
1
0x49
2
0x50
3
0x51
4
0x52
5
0x53
6
0x54
7
0x55
const int *k = &j
j
&j
(const) j
represents that ‘k’ is a non constant type pointer and the value to which it is pointing
is constant type. Therefore, value of ‘j’ can not be changed while address of ‘k’ can be
changed.
✞
1 #include <iostream >
using namespace std;
2.2. POINTER 215
3
int main () {
5 int i = 2;
const int j = 3;
7 const int *k = &j;
// int const *k = &j; // Or state
9 cout << "Address of k is " << k << endl ;
k = &i; // k points to i. *k is 2. Pointer changes
11 cout << "New address of k is " << k << endl ;
//
13 cout << "i : " << i << ", k : " << *k << endl ;
return 0;
15 }
✌
✆
✞
Address of k is 0x22ff44
New address of k is 0x22 ff48
i : 2, k : 2
✌
✆
Similarly, if
✞
1 // +--Pointer type , i.e. constant pointer
// |
3 int * const k = &j;
✌
✆
then, pointer becomes constant while value of pointee can be changed. Notice the position
of asterisk (*) not the const keyword.
1
0x49
2
0x50
3
0x51
4
0x52
5
0x53
6
0x54
7
0x55
int * const k = &j
(const) *k
j
&j
✞
1 #include <iostream >
using namespace std;
3
int main () {
5 int i = 2;
int j = 3;
7 int * const k = &j;
cout << "Address of k is " << k << endl ;
9 cout << "Old values - j : " << j << ", k : " << *k << endl ;
j = 5; // k points to i. *k is 2. Pointer changes
11 cout << "New values - j : " << j << ", k : " << *k << endl ;
//k = &i;// Error! assignment of read -only variable ’k’
13 return 0;
}
✌
✆
216 Array & Pointer
✞
Address of k is 0x22ff44
Old values - j : 3, k : 3
New values - j : 5, k : 5
✌
✆
The change in the position of the asterisk (*) and keyword const changes the pointer and
pointee type. The general representation is
✞
1 int n = 5;
int * p = &n; // non -const -Pointer to non -const -Pointee
3 const int * p = &n; // non -const -Pointer to const - Pointee
int * const p = &n; // const -Pointer to non -const - Pointee
5 const int * const p = &n; // const -Pointer to const -Pointee
✌
✆
2.2.9 Pointers to Function
A pointer to function is defined as
✞
1 void (*fp)();
✌
✆
This function has no return value and no arguments (i.e. parameters). Here parentheses
( ) is used to encapsulate asterisk and function name. The reason is that parentheses
operator, ( ), has higher precedence than that of dereferencing operator (*). Hence for
pointer-to-function variable, dereferencing of function is grouped by parentheses. Exam-
ple for pointer-to-function is given below.
✞
1 #include <iostream >
3 using namespace std;
5 void myFunc () {
cout << "Function is called ..." << endl ;
7 }
9 int main (int argc , char *argv []) {
void (*r)();
11 r = myFunc;
(*r)();
13 return 0;
}
✌
✆
✞
Function is called ...
✌
✆
A pointer to a function is possible in C++. This type of function may accepts arguments
as pointers. The return value from the function is pointed by the function itself. In
following example, a pointer-to-function is used.
✞
1 #include <iostream >
using namespace std;
2.2. POINTER 217
3
int* f(int* x) {
5 (*x)++;
return x;
7 }
9 int main (int argc , char *argv []) {
int a = 1;
11 cout << f(&a) << endl ;
cout << *f(&a) << endl ;
13 return 0;
}
✌
✆
✞
0x22ff5c
3
✌
✆
Sometimes pointer-to-function returns the pointer to local variable. It is not considered
a good practice. Compiler shows warning when we do so. It should be avoid in program-
ming.
2.2.10 Pointer Arithmetic
In normal mathematics numbers are used for addition, subtraction, division and multipli-
cation etc. A pointer to an integer has different behavior to the integer. This is why, in
pointer arithmetic, we have to arrange or conform the pointers so that they can behave in
properly. A pointer-to-variable always points to the address where value of the variable
is stored. This is why direct arithmetic of the pointers is of the arithmetic of the address
rather than the values stored at the addresses. For example, we have to create an array
of 2 element size (cells). Store a value in first cell. Retrieve the value and increment it
by one. In the following example, we implement the solution as given below:
✞
#include <iostream >
2 using namespace std;
4 int main (int argc , char *argv []) {
int i [10];
6 int* a = i;
cout << "a is " << (long ) a << endl ;
8 a++;
cout << "a++ is " << (long ) a << endl ;
10 return 0;
}
✌
✆
✞
a is 2293556
a++ is 2293560
✌
✆
In above example, the increment operator adds 4 to the address of pointer-to-integer
variable ‘a’ rather that its value. This is why, we need proper confer to the pointer to
218 Array & Pointer
the desired result. In the following example, we uses proper way of pointe and get the
desired result.
✞
#include <iostream >
2 using namespace std;
4 int main (int argc , char *argv []) {
int i [2]={1}; /*1st=1, 2nd=0*/
6 int* a = i;
cout << "a is " << *a << endl ;
8 *a++; /* Increment to pointer index*
*and get value which is 0 */
10 cout << "a++ is " << *a << endl ;
return 0;
12 }
✌
✆
✞
a is 1
a++ is 0
✌
✆
The result is not as we sought in result. Above code is again modified as given below:
✞
#include <iostream >
2 using namespace std;
4 int main (int argc , char *argv []) {
int i [2]={1}; /*1st=1, 2nd=0*/
6 int* a = i;
cout << "a is " << *a << endl ;
8 (*a)++; /* Increment to value of a*/
cout << "a++ is " << *a << endl ;
10 return 0;
}
✌
✆
✞
a is 1
a++ is 2
✌
✆
This is the result what we sought in our problem. Similarly, in following example, we use
pointers in simple arithmetic.
✞
#include <iostream >
2 using namespace std;
4 int main (int argc , char *argv []) {
int a = 9, b = 5;
6 int* i = &a;
int* j = &b;
8 cout << "Sum of i, j is " << (*i + *j) << endl ;
cout << "Subtraction of i, j is " << (*i - *j) << endl ;
10 cout << "Division of i, j is " << (*i / *j) << endl ;
cout << "Multiplication of i, j is " << (*i * *j) << endl ;
2.2. POINTER 219
12 return 0;
}
✌
✆
✞
Sum of i, j is 14
Subtraction of i, j is 4
Division of i, j is 1
Multiplication of i, j is 45
✌
✆
220 Accessing System Files
3.1. STREAM & BUFFER 221
3Accessing System Files
Standard Input-Output and access of files is a main part of computer programming. In
this chapter we shall discuss the importance and methodology of accessing system and
user define files.
3.1 Stream & Buffer
3.1.1 File Stream
fstream is a header which includes the objects for reading a file or writing a file. It is just
a file stream. Operations on the open file are performed by the objects/member functions
of the fstream class.
3.1.2 File Buffer
filebuf is a stream buffer that is used to read from a file or write to a file. It is constructed
without association, these objects are associated to a file by calling its member open. Once
open, all input/output operations performed on the object are reflected in the associated
file. rdbuf () reads the file at once completely and put it in read buffer stream. See the
example below:
✞
#include <fstream >
2 #include <iostream >
using namespace std;
4
int main (int argc , char * argv []) {
6 ifstream inF("a.txt");
cout << inF.rdbuf();
8 return 0;
}
✌
✆
streambuf is a stream buffer and is an object in charge of performing the reading and
writing operations of the stream object it is associated with. The stream delegates all
such operations to its associated stream buffer object, which is an intermediary between
the stream and its controlled input and output sequences.
3.2 Accessing Files
Files are named memory locations where data is stored in text or binary form. Each
file that exists in the disk can be accessed, read and write if it is not specially granted
restricted permissions. Users may create, access, update and delete a file by using C++
program.
222 Accessing System Files
3.2.1 Open A File
A file in C++ can be opened in read, write, truncate or append mode. The flags used to
open a file are given in following table.
Flags Meaning
ios::in Opens an input file without truncating the existing file. (ifstream)
ios::ate Opens an existing file and seeks the end.
ios::out Opens an output file. By default, ios::trunc is implied. (ofstream)
ios::app Opens an output file for appending data.
ios::nocreate Opens a file only if it already exists.
ios::noreplace Opens a file only if it does not exist.
ios::trunc Opens a file in truncate mode.
ios::binary Opens a file in binary mode. Default is text mode.
Table 3.1: File opening mode.
To open a file, one can either call open on the file stream or, more commonly, use the
constructor. One can also supply an open mode to further control the file stream. For
reading-writing of the file, ‘fstream’ header file is used.
✞
1 #include <fstream >
using namespace std;
3
int main (int argc , char *argv []) {
5 ofstream file1;
7 file1.open ("file1.txt", ios:: app);
file1 << "Appended data .n";
9
ofstream file2("file2.txt");
11 file2 << "Replace data .n";
13 return 0;
}
✌
✆
Each file opened must be closed by using function close(). On unsuccessful, a flag is set in
the stream object. The flag status is checked by good(), bad() or fail() member functions,
which return a boolean value. The stream object doesn’t throw any exceptions in such a
situation, hence manual status check is required.
✞
#include <iostream >
2 #include <fstream >
using namespace std;
4
3.2. ACCESSING FILES 223
int main (int argc , char *argv []) {
6
/* Try to open non -exist file xyz.txt.*
8 *fstream does not show any errors. */
ifstream file1;
10 file1.open ("zyz.txt", ios::in);
12 /*To check whether a xyz.txt is really*
*opened or not , we use good () object.*/
14 cout << file1.good (); /* Returns 0*/
cout << endl ;
16
/* Try to open existing file a.txt. */
18 ifstream file2;
file2.open ("a.txt", ios::in);
20
/*To check whether a a.txt is really *
22 *opened or not , we use good () object.*/
cout << file2.good (); /* Returns 1*/
24 }
✌
✆
✞
0
1
✌
✆
fail() tries to read the next character from the input stream. If it fails to read the next
character due to EOF, it returns true otherwise it returns false.
✞
#include <iostream >
2 using namespace std;
4 int main (int argc , char ** argv ) {
char name ;
6 cout << "Enter the name : ";
cin.get(name );
8 while (cin.fail () == false) {
cout << name << endl ;
10 cin.get(name );
}
12 return 0;
}
✌
✆
3.2.2 Read File Data
While reading a file, input from the in-stream is assigned to a string variable, until the
file or in-stream does not reach to EOF pitfall or until an error does not occur. getline()
function is used for this purpose.
✞
1 #include <fstream >
#include <string >
224 Accessing System Files
3 #include <iostream >
using namespace std;
5
int main (int argc , char ** argv ) {
7 /* Line number counter */
int linecount = 0;
9 string line ;
/* Open input file */
11 ifstream inFile("file1.txt");
/*If input file is successfully opened.*/
13 if (inFile) {
/* Read line by line of text file . *
15 *until end of file is not found. */
while (getline(inFile , line )) {
17 /* Print the line number and line */
cout << linecount << ": " << line << ’n’;
19 /* Increment the line number */
linecount ++;
21 }
}
23 /* Close input file .*/
inFile.close();
25 return 0;
}
✌
✆
We can also read a file byte by byte as the method given below:
✞
#include <fstream >
2 #include <string >
#include <iostream >
4 using namespace std;
6 int main (int argc , char ** argv ) {
ifstream is("file1.txt");
8
char c;
10 while (is.get(c))
cout << c << endl ;
12
is.close();
14
return 0;
16 }
✌
✆
To check whether the file has been reached to its end, eof () member function is used as
shown in the syntax given below.
✞
if (infile.eof()) break
✌
✆
3.2. ACCESSING FILES 225
Infile Stream
ifstream operator is used to open an input file stream. It is always followed by input
stream name. A file name is argument of the input stream name. To use this operator,
header file ‘fstream’ is required. Syntax of ifstream is given as
✞
1 ifstream <stream name >("<file name >");
✌
✆
An example is given below:
✞
1 #include <string >
#include <fstream >
3 using namespace std;
5 int main (int argc , char *argv []) {
/* Open a file stream to read */
7 ifstream f1("a.txt");
ofstream f2("b.txt");
9 string s;
while (getline(f1 , s))
11 f2 << s << "n";
}
✌
✆
On execution, we shall get desired result.
3.2.3 Write File Data
The data of user is stored in memory as data file. To write a file in memory, data is first
transfer to out stream buffer and them it is flushed into the memory.
Outfile Stream
ofstream operator is used to open an output file stream. This is member of fstream (file
stream) class. It is always followed by output stream name. A file name is argument of
the output stream name. To use this operator, header file ‘fstream’ is required. Syntax
of ofstream is given as
✞
ofstream <stream name >("<file name >");
✌
✆
An example is given below:
✞
1 #include <string >
#include <fstream >
3 using namespace std;
5 int main (int argc , char *argv []) {
ifstream f1("a.txt");
7 /* Open a file stream to write*/
ofstream f2("b.txt");
9 string s;
while (getline(f1 , s))
226 Accessing System Files
11 f2 << s << "n";
f1.close();
13 f2.close()’
return 0;
15 }
✌
✆
On execution, we shall get desired result. Concatenation of the strings is allowed in C++
by using operator ‘+=’. See the example below:
✞
1 #include <string >
#include <fstream >
3 #include <iostream >
using namespace std;
5
int main (int argc , char *argv []) {
7 ifstream f1("a.txt");
/* Open a file stream to write*/
9 ofstream f2("b.txt");
string s, line ;
11 while (getline(f1 , s))
line += s + "n";
13 f2 << line ;
cout << line ;
15 }
✌
✆
3.2.4 File As Function Argument
A input or output file stream allows to pass a file pointer to a function as its argument.
The syntax of argument is like
✞
1 ifstream & <arg name > // for input file stream
ofstream & <arg name > // for output file stream
✌
✆
In the following example, out file stream is passed to function argument and contents are
written in the out file.
✞
#include <iostream >
2 #include <fstream >
using namespace std;
4
void PassToFunc (ofstream &f, int n) {
6 f << n;
}
8
int main () {
10 ofstream f1("b.txt");
PassToFunc (f1 , 10);
12 return 0;
}
✌
✆
It creates a file “b.txt” in which integer 10 is written.
3.2. ACCESSING FILES 227
3.2.5 File Position
We can access the location of file pointer by using tellp() for an out stream (ostream) and
tellg() for an in stream (istream). seekp return the stream position (streampos) of an out
stream (ostream) and seekg() returns the stream position of an in stream (istream). seekp
and seekg() takes two arguments. First is number of byte, either positive or negative value
and second is direction. The seek directions are
Flags Meaning
ios::beg From the beginning of stream.
ios::cur From the current position of stream.
ios::end From the end of stream.
Table 3.2: Seek Directions.
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
(1)
fp
(2)
fp.seekp(-8, ios::cur)
(3)
fp
(4)
Figure 3.1: Change in location of file pointer from current file pointer location.
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
(1)
fp
(2)
fp.seekp(-8, ios::end)
(3)
fp
(4)
Figure 3.2: Change in location of file pointer from the end of file location.
228 Accessing System Files
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
(1)
fp
(2)
fp.seekp(10, ios::beg)
(3)
fp
(4)
Figure 3.3: Change in location of file pointer from the beginning of file location.
In following example, a file ‘a.txt’ is read and file pointer is set after 10bytes using
seekg() function from the beginning of the file. The current position of the in file stream
is return by using function tellg() function.
✞
1 #include <fstream >
#include <iostream >
3 using namespace std;
5 int main (int argc , char * argv []) {
/* Open in file */
7 ifstream inf("a.txt");
/* Set file pointer after 10 bytes*
9 *from beginning of current file */
inf.seekg(10, ios:: cur);
11 /* Get current position of file pointer */
cout << inf.tellg();
13 return 0;
}
✌
✆
✞
10
✌
✆
In following example, we set the file pointer after 10 bytes from the end of the file location.
✞
1 #include <fstream >
#include <iostream >
3 using namespace std;
5 int main (int argc , char * argv []) {
/* Open in file */
7 ifstream inf("a.txt");
/* Set file pointer after -10 bytes*
9 *from the end of the current file */
inf.seekg(-10, ios:: end);
11 /* Get current position of file pointer */
cout << inf.tellg();
3.3. DATA STRUCTURES 229
13 return 0;
}
✌
✆
✞
228
✌
✆
For output stream, seekp() and tellp() functions are used.
✞
1 #include <fstream >
#include <iostream >
3 using namespace std;
5 int main (int argc , char * argv []) {
/* Open out file */
7 ofstream outf ("b.txt");
/* Set file pointer after 11 bytes*
9 *from beginning of current file */
outf . seekp(11, ios:: beg);
11 /* Get current position of file pointer */
cout << outf .tellp();
13 return 0;
}
✌
✆
✞
11
✌
✆
We can write something after the specific position in the current out file by using ‘<<’
operator.
✞
1 #include <fstream >
#include <iostream >
3 using namespace std;
5 int main (int argc , char * argv []) {
ofstream outf ("b.txt");
7 outf . seekp(11, ios:: beg);
outf << "This is my file ";
9 return 0;
}
✌
✆
3.3 Data Structures
A data structure (struct) contains multiple pieces of data. Each piece of data (called a
“member”) can be accessed by using a group of instance of structure, followed by a ‘.’
(ie dot), then the name of the member (another way to access a member is using the
member operator ‘−>’ for pointers.). The member variables of data structure can be of
any data-type or can be an array or a pointer.
230 Accessing System Files
3.3.1 Struct
A data structure contains multiple pieces of data. One defines a data structure using the
struct keyword. For example,
✞
struct <mystruct >{
2 int <int_member >;
double <double_member >;
4 char <string_member [25] >;
} <variable >;
✌
✆
‘variable’ is an instance of ‘mystruct’. One can omit it from the end of the struct decla-
ration and declare it later using:
✞
1 struct <mystruct > <variable >;
✌
✆
It is often common practice to make a type synonym so we don’t have to type struct
‘mystruct’ all the time. The struct itself has no name (by the absence of a name on the
first line), but it is aliased as ‘mystruct’. Then you can use
✞
1 <mystruct > <variable >;
✌
✆
We can add or read data in structure by just using ‘dot’ symbol as
✞
1 struct student {
int id;
3 char *name ;
float perc ;
5 } st;
st.id =1;/* use of dot symbol between instance name and struct
element.*/
✌
✆
After creating an instance of structre, instance reserves the memory bytes equal to the
sum of size of all members. See the figure given below:
a b c d e f g h i j
st
id name perc
Here is working example of struct function:
✞
#include <iostream >
2 using namespace std;
4 struct student {
int id;
6 char *name ;
float perc ;
8 } st , st1 , st2;
3.3. DATA STRUCTURES 231
10 int main (int argc , char *argv []) {
st.id = 1;
12 st1.name = "Arun Umrao";
st2.perc = 90.5;
14 cout << "Id is: " << st.id << endl ;
cout << "Name is: " << st1.name << endl ;
16 cout << "perc is: " << st2.perc << endl ;
return 0;
18 }
✌
✆
✞
Id is: 1
Name is: Arun Umrao
perc is: 90.5
✌
✆
Another simple example is given below.
✞
1 #include <iostream >
using namespace std;
3
struct data {
5 int val;
float b;
7 };
9 int main (int argc , char *argv []) {
struct data s;
11 s.val = 12;
s.b = 3.14159;
13 cout << "The val field in s is:" << s.val << endl ;
return 0;
15 }
✌
✆
✞
The val field in s is: 12
✌
✆
Pointer can be also used in structure. An instance of a structure ‘data’ using a pointer is
declared as
✞
1 data *<variable >;
✌
✆
Member values of the structure declared with pointer are initialized or accessed by using
operator −
>. See the following syntax, in which a structure ‘Func’ is declared by using a
pointer and its member values are set by using operator −
>.
✞
1 struct Func {
int val;
3 float fl;
};
5 struct Func *b;
b->val = 3491;
✌
✆
232 Accessing System Files
st st++
val fl
A working example is
✞
#include <iostream >
2 using namespace std;
4 struct Func {
int val;
6 float fl;
};
8
int main (int argc , char *argv []) {
10 /* Func struct required for pointer */
struct Func a;
12 /* this is a pointer to a struct Func */
struct Func *b;
14 b->val = 3491;
cout << "The value of b is " << b->val << endl ;
16 return 0;
}
✌
✆
✞
The value of b is 3491.
✌
✆
A struct data can also be passed to a function by using address of procedure. See the
example below in which data struct is passed to function ‘Plantation’.
✞
1 #include <iostream >
using namespace std;
3
/* Data structure */
5 struct Data {
int Trees;
7 int Plants;
};
9
/* function Plantation with data structure as pointer */
11 void Plantation (struct Data *f) {
f->Trees = 10;
13 f->Plants = 20;
}
15
int main (int argc , char *argv []) {
17 /* Struct data structure */
struct Data Bio;
19 /* Pass address ‘Bio ’ into struct ‘Data ’ as pointer */
Plantation (& Bio);
3.3. DATA STRUCTURES 233
21 cout << "Trees : " << Bio.Trees << endl ; /* prints "10" */
cout << "Plants : " << Bio.Plants << endl ; /* prints "20" */
23 return 0;
}
✌
✆
✞
Trees : 10
Plants : 20
✌
✆
A constant pointer, once holds an address cannot change to the new address. It means a
constant pointer, if already pointing to an address, cannot point to a new address.
✞
#include <iostream >
2 using namespace std;
4 int main (int argc , char *argv []) {
char ch = ’A’;
6 char cH = ’B’;
8 char * const ptr = &ch; // A constant pointer
ptr = &cH; // Illegal way of pointer .
10
return 0;
12 }
✌
✆
In case of pointer to structure, if the things on the left of the ‘.’ (dot) or ‘−
>’ operator is
qualified (with ‘const’ or ‘volatile’) then the result is also has those qualifiers associated
with it. In the following example, when the pointer points to a qualified type the result
got is also qualified.
✞
#include <iostream >
2 using namespace std;
4 struct myStruct {
int i;
6 };
8 int main (int argc , char *argv []) {
/* Initialisation of structures . */
10 struct myStruct *Ptr , s_item;
/* Initialisation of structures of constant qualifier . */
12 const struct myStruct *s_Ptr;
/* Set the item value.*/
14 s_item.i = 1; /* OK */
/* Assigning new pointer .*/
16 Ptr = &s_item;
Ptr ->i += 2; /* OK */
18 /* Constant qualified pointer.*/
s_Ptr = &s_item;
20 s_Ptr ->i = 0; /* Not OK to point constant type qualifier . */
return 0;
234 Accessing System Files
22 }
✌
✆
A structure can also be initialized at the starting of program if structure is defined as
✞
struct employee {
2 int no;
int sex;
4 int age;
};
6 struct employee EmpNo={<int >, <int >, <int >};
✌
✆
The following example clears the initialization of the structure.
✞
#include <iostream >
2 using namespace std;
4 struct employee {
int no;
6 int sex;
int age;
8 };
10 int main (int argc , char *argv []) {
struct employee EmpNo = {10, 1, 15}; /* Initializing structure */
12 cout << EmpNo.no << endl << EmpNo.sex << endl << EmpNo.age;
return 0;
14 }
✌
✆
Nested Structure
When a loop is declared inside another loop then the inner loop is called nested loop.
✞
for (;;) {
2 for (;;) /* Nested for loop */
}
✌
✆
Similarly, when a structure is declared inside another structure then it is called nested
structure. Nested structure can be declared by using either normal variable or pointer.
In following example, a nested structure is declared and declared by simple variable.
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char *argv []) {
5
/* date structure */
7 struct date {
int day;
9 int month;
int year ;
3.3. DATA STRUCTURES 235
11 };
13 /* variety structure */
struct variety {/* Upper level structure */
15 char *name ;
/* Nested structure . Declared by normal variable . *
17 * Element of the structure are accessed by dot (.)*/
struct date date ; /* Lower level structure as normal
variable .*/
19 } tr; /* Structure declared as normal variable . *
* Elements can be accessed by (.) symbol.*/
21
/* Accessing structure elements by using synopsis like
23 * up_level_struct (.) up_level_elem
* or
25 * up_level_struct (.) low_level_struct (.) low_level_elem */
tr.name = "A";
27 tr.date .day = 10;
cout << "Name : " << tr.name << endl ;
29 cout << "day : " << tr.date .day << endl ;
return 0;
31 }
✌
✆
✞
Name : A
day : 10
✌
✆
In simple variable type declaration of structure, elements are accesses by using dot (.).
Using of pointer symbol (−>) throws the errors. In above example, ‘name’ and ‘date’ are
elements of the ‘variety’ structure.
✞
#include <iostream >
2 using namespace std;
4 int main (int argc , char *argv []) {
6 /* date structure */
struct date {
8 int day;
int month;
10 int year ;
};
12
/* variety structure */
14 struct variety {/* Upper level structure */
char *name ;
16 /* Nested structure . Declared by normal variable . *
* Element of the structure are accessed by dot (.)*/
18 struct date date ; /* Lower level structure as normal
variable .*/
} tr; /* Structure declared as normal variable . *
20 * Elements can be accessed by (.) symbol.*/
236 Accessing System Files
22 /* Accessing structure elements by using synopsis like
* up_level_struct (.) up_level_elem
24 * or
* up_level_struct (.) low_level_struct (.) low_level_elem */
26 tr.name = "A";
tr.date .day = 10;
28 /* Following line throws errors. Reason is that we are trying*
*to access the element by pointer symbol (->) even though *
30 *the structure ‘tr ’ is declared here as normal variable . */
tr ->date .month = 11;
32 cout << "Name : " << tr.name << endl ;
cout << "day : " << tr.date .day << endl ;
34 return 0;
}
✌
✆
By other way, we can use pointer method to assign one structure inside other structure.
In pointer method, elements are accessed by using pointer symbol (−>) and dot (.).
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char *argv []) {
5
/* date structure */
7 struct date {
int day;
9 int month;
int year ;
11 };
13 /* variety structure */
struct variety {/* Upper level structure */
15 char *name ;
/* Nested structure . Declared by normal variable . *
17 * Element of the structure can accessed by dot (.)*/
struct date date ; /* Lower level structure as normal
variable .*/
19 } *tr; /* Structure declared as pointer variable . *
* Elements can be accessed by (->) symbol.*/
21 /* Accessing structure elements by using synopsis like
* up_level_struct (->) up_level_elem
23 * or
* up_level_struct (->) low_level_struct (.) low_level_elem */
25 tr ->name = "A";
tr ->date .day = 10;
27 cout << "Name : " << tr ->name << endl ;
cout << "day : " << tr ->date .day << endl ;
29 return 0;
}
✌
✆
3.3. DATA STRUCTURES 237
✞
Name : A
day : 10
✌
✆
Again, indirect membership operator or structure pointer operator (−>) is not used in
the level or element of the structure declared as normal variable.
✞
#include <iostream >
2 using namespace std;
4 int main (int argc , char *argv []) {
6 /* date structure */
struct date {
8 int day;
int month;
10 int year ;
};
12
/* variety structure */
14 struct variety {/* upper level structure */
char *name ;
16 /* Nested structure . Declared by normal variable . *
* Element of the structure are accessed by dot (.)*/
18 struct date date ; /* Lower level structure as normal
variable .*/
} *tr; /* Structure declared as pointer variable .*
20 * Elements are accessed by (->) symbol. */
/* Following lines throw errors. We are trying here to access *
22 *the elements of structure ‘date ’ by pointer symbol (->) while*
*the structure ‘date ’ is declared here as normal variable .
*/
24 tr ->date ->day = 10;
tr.date ->day = 10;
26 return 0;
}
✌
✆
But the lower level elements can also be accessed by using pointer symbol (−>) if lower
level structure is also declared as pointer level.
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char *argv []) {
5
/* date structure */
7 struct date {
int day;
9 int month;
int year ;
11 };
238 Accessing System Files
13 /* variety structure */
struct variety {/* upper level structure */
15 char *name ;
/* Nested structure . Declared as pointer variable .*
17 * Element of the structure can accessed by (->) */
struct date *date ; /* Lower level structure as normal
variable .*/
19 } *tr; /* Structure declared as pointer variable . *
* Elements can be accessed by (->) symbol.*/
21 cout << "Date & Month :" << endl ;
/* Accessing structure elements by using synopsis like
23 * up_level_struct (->) up_level_elem
* or
25 * up_level_struct (->) low_level_struct (->) low_level_elem */
tr ->date ->day = 10;
27 tr ->date ->month = 10;
cout << "Day : " << (tr ->date ->day) << endl ;
29 cout << "Month : " << (tr ->date -> month) << endl ;
return 0;
31 }
✌
✆
✞
Date & Month :
Day : 10
Month : 10
✌
✆
In above examples, it is clarified that, elements of structures declared as variable type are
accessed by using dot (.) and elements of structure declared as pointer type are accessed
by using indirect membership operator or structure pointer operator (-¿).
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char *argv []) {
5
/* date structure */
7 struct date {
int day;
9 int month;
int year ;
11 };
13 /* variety structure */
struct variety {/* up_level_struct (uls)*/
15 char *name ;
/* Nested structure . Declared as pointer variable .*
17 * Element of the structure are accessed by (->). */
struct date *date ; /* Lower level structure as normal
variable .*/
19 } tr; /* Structure declared as normal variable .*
* Elements can be accessed by dot (.). */
21
3.3. DATA STRUCTURES 239
/* Accessing structure elements by using synopsis like
23 * up_level_struct (.) up_level_elem
* or
25 * up_level_struct (.) low_level_struct (->) low_level_elem */
tr.date ->day = 10;
27 tr.date ->month = 10;
cout << "Day : " << (tr.date ->day) << endl ;
29 cout << "Month : " << (tr.date -> month) << endl ;
return 0;
31 }
✌
✆
✞
Day : 10
Month : 10
✌
✆
Linked List
See the followomg prototype for the definition of a structure:
✞
struct list_Elem {
2 int data ;
struct list_Elem *ele_Ptr ; /* Element is structure itself.*/
4 };
✌
✆
In this prototype, element of structure is structure itself. It is forbidden in the structure
definition. But in fact it only contains a pointer to itself. It is allowed as by the time
the compiler reaches the pointer declaration it already knows that there is such a thing
as a ‘struct list Elem’ so the declaration is permitted. In fact, it is possible to make a
incomplete declaration of a structure by saying
✞
struct list_Elem ;
✌
✆
at some point before the full declaration. This will allow the declaration of pointers before
the full declaration is seen. It is also important in the case of cross-referencing structures
where each must contain a pointer to the other, as shown in the following example.
✞
1 struct s_1; /* Incomplete type */
3 struct s_2 {
int something ;
5 struct s_1 *sp;
};
7
struct s_1 { /* Full declaration */
9 float something ;
struct s_2 *sp;
11 };
✌
✆
This illustrates the need for incomplete types. It also illustrates an important thing about
the names of structure members: they inhabit a name-space per structure, so element
240 Accessing System Files
names can be the same in different structures without causing any problems. Incomplete
types may only be used where the size of the structure isn’t needed yet. A full declaration
must have been given by the time that the size is used. The later full declaration mustn’t
be in an inner block because then it becomes a new declaration of a different structure.
✞
1 struct x; /* Incomplete type */
3 /* valid uses of the tag */
struct x *p, func (void );
5
void f1(void ) {
7 struct x {
int i;
9 }; /* redeclaration ! */
}
11
/* full declaration now */
13 struct x {
float f;
15 } s_x;
17 void f2(void ) {
/* valid statements */
19 p = &s_x;
*p = func ();
21 s_x = func ();
}
23
struct x func (void ) {
25 struct x tmp;
tmp.f = 0;
27 return (tmp);
}
✌
✆
The other principal way to get incomplete types is to declare arrays without specifying
their size and their type is incomplete until a later declaration provides the missing
information:
✞
int ar []; /* incomplete type */
2 int ar [5]; /* completes the type */
✌
✆
If you try that out, it will only work if the declarations are outside any blocks (external
declarations), but that’s for other reasons. There were three elements linked into the list,
which could have been built like this:
✞
struct list_Elem {
2 int data ;
struct list_Elem *pointer ;
4 } ar [3];
6 int main (int argc , char *argv []) {
3.3. DATA STRUCTURES 241
ar [0]. data = 5;
8 ar [0]. pointer = &ar [1];
ar [1]. data = 99;
10 ar [1]. pointer = &ar [2];
ar [2]. data = -7;
12 ar [2]. pointer = 0; /* mark end of list */
return (0);
14 }
✌
✆
and the contents of the list can be printed in two ways. The array can be traversed in
order of index, or the pointers can be used as in the following example.
✞
#include <iostream >
2 using namespace std;
4 struct list_Elem {
int data ;
6 struct list_Elem *pointer ;
} ar [3];
8
int main (int argc , char *argv []) {
10
struct list_Elem *lp;
12
ar [0]. data = 5;
14 ar [0]. pointer = &ar [1];
ar [1]. data = 99;
16 ar [1]. pointer = &ar [2];
ar [2]. data = -7;
18 ar [2]. pointer = 0; /* mark end of list */
20 /* follow pointers */
lp = ar;
22 while (lp) {
cout << "contents " << lp ->data << endl ;
24 lp = lp ->pointer ;
}
26 return 0;
}
✌
✆
✞
contents 5
contents 99
contents -7
✌
✆
Structure As Arguments
A structure can also passed to a function as shown in the example below:
✞
1 #include <iostream >
using namespace std;
242 Accessing System Files
3
#define TREE_NUM 50
5
/* Structure for garden tree length.*/
7 struct g_len {
char gardens[TREE_NUM ];
9 double t_len_1;
double t_len_2;
11 };
13 /* Structure passed to the function .*/
double sum(struct g_len val) {
15 return (val.t_len_1 + val.t_len_2 );
}
17
int main (int argc , char *argv []) {
19 /* Initialized the structure .*/
struct g_len sbi = {
21 "G DELHI",
6524.12 ,
23 9458.87
};
25 double s=sum(sbi);
cout << "Tree length is " << s << endl ;
27 return 0;
}
✌
✆
✞
Tree length is 15982.99 m.
✌
✆
3.3.2 Enumerate
In C++, enumerations are created by explicit definitions, which use the enum keyword
and are reminiscent of struct and union definitions. Point of declaration of enum is that
point of the program body, where, enum list is started. See example below.
✞
1 #include <iostream >
using namespace std;
3
enum {
5 /*0*/ /*1*/ /*2*/
TRUE , FALSE , NO
7 } b = NO;
9 int main (int argc , char ** argv ) {
cout << "bool : " << b << endl ;
11 return 0;
}
✌
✆
3.3. DATA STRUCTURES 243
✞
bool : 2
✌
✆
C also allows the programmer to choose the values of the enumeration constants explicitly,
even without type.
✞
1 #include <iostream >
using namespace std;
3
enum {
5 TRUE = 0, FALSE = 1, NO = 10
} b = NO;
7
int main (int argc , char ** argv ) {
9 cout << "bool : " << b << endl ;
return 0;
11 }
✌
✆
✞
bool : 10
✌
✆
In enumerate the values are assigned successively. If any enum key is set to a specific
value then next enum key has value one larger than its preceding enum key if its value is
not set.
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char ** argv ) {
5
enum COLORS {
7 BLUE , /* Index value 0*/
GREEN = 3, /* Index value 3*/
9 YELLOW , /* Index value 4*/
RED = 2, /* Index value 2*/
11 BLACK /* Index value 3*/
};
13 cout << "The colors are:n";
cout << BLUE << endl ; /*0*/
15 cout << YELLOW << endl ; /*4*/
cout << BLACK << endl ; /*3*/
17
return 0;
19 }
✌
✆
✞
The colors are:
0
4
3
✌
✆
244 Accessing System Files
3.3.3 Union
The definition of a union is similar to that of a struct. The difference between the two
is that in a struct, the members occupy different areas of memory, but in a union, the
members occupy the same area of memory. Thus, in the following type, for example:
✞
union {
2 int i;
double d;
4 } u;
✌
✆
The programmer can access either ‘u.i’ or ‘u.d’, but not both at the same time. Since ‘u.i’
and ‘u.d’ occupy the same area of memory, modifying one modifies the value of the other,
sometimes in unpredictable ways. The size of a union is the size of its largest member.
A simple example is
✞
#include <iostream >
2 #include <string >
using namespace std;
4
union Data {
6 int i;
float f;
8 char str [50];
};
10
int main (int argc , char ** argv ) {
12 union Data data ;
data .i = 10;
14 data .f = 220.5;
string str("C Programming ");
16 str.copy (data .str , str.length());
data .str[str.length ()]=’0’;
18 cout << "data .i : " << data .i << endl ;
cout << "data .f : " << data .f << endl ;
20 cout << "data .str : " << data .str << endl ;
return 0;
22 }
✌
✆
✞
data .i : 1917853763
data .f : 4.12236 e+30
data .str : C Programming
✌
✆
A constructor and destructor member function can also be declared inside the union.
union has few restrictions like
1. A union cannot have virtual functions, members of reference type and base classes.
It cannot be used as a base class.
2. If a union has a member with a user-defined constructor, a copy operation, a move
operation, or a destructor, then that special function is deleted for that union; that
is, it cannot be used for an object of the union type.
3.4. MEMORY MANAGEMENT 245
3. At most one member of a union can have an in-class initializer.
3.4 Memory Management
3.4.1 Create Memory Space
If there is requirement of a few bytes of memory to store data then we allocate memory
space by using simple variables. But in case of array, string and stacks where addition
of data is not static a dynamic memory allocation is required. Arrays, strings and stack
stores non-counting data when a program is in run thus the memory size should be
expanded when a new data is added. Allocation of memory while program is in run
is called dynamic memory allocation. To create a dynamic memory space, we use new
keyword for this purpose. Its syntax is
✞
1 int *i = new int [10];/*A block of ten integers .*/
int *j = new int (10) ; /* Heap allocation for 10 integers .*/
✌
✆
The new returns the address of first element of the array to the pointer ‘i’. Each time a
dynamic memory is created, must be freed before exit from the program by using delete
keyword.
✞
delete i;
✌
✆
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char ** argv ) {
5 int *i = new int [5];
int j;
7 for (j = 0; j < 5; j++) {
i[j] = j;
9 }
11 for (j = 0; j < 5; j++) {
cout << i[j] << endl ;
13 }
delete i;
15 return 0;
}
✌
✆
✞
0
1
2
3
4
✌
✆
246 Accessing System Files
3.4.2 Delete Memory Space
Each memory heap created dynamically by new operator must be freed by using delete
keyword.
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char ** argv ) {
5 int *i = new int [5]; // Create space for 5 integers
delete i; // Clear the space
7 return 0;
}
✌
✆
3.4.3 Placement Memory Space
new() operator is used to place a memory space over the given buffer stack. For example,
‘b’ is declared as a buffer of two element. The new() operator
✞
int b[2];
2 /* Create memory space and filled with 5*/
int *i = new(b) int (5);
✌
✆
places a memory space over buffer and puts the integer value ‘5’. The address of this
element is assigned to variable ‘i’. Similarly,
✞
1 int *i = new(b + sizeof (int)) int (6);
✌
✆
puts the integer value ‘6’ over the buffer at memory location 4 bytes (size of integer)
ahead to the address of buffer ‘b’. See the example below:
✞
1 #include <iostream >
using namespace std;
3
int main () {
5 int b[2];
int *i = new(b) int (5);
7 int *j = new (b + sizeof (int)) int (6);
cout << *i << endl ;
9 cout << *j << endl ;
return 0;
11 }
✌
✆
✞
5
6
✌
✆
Placements are not deallocated by using delete keyword.
3.5. STACK 247
3.5 Stack
C++ has a ‘stack’ library which deals with all stack related activities. An stack is initiated
as
✞
stack <int > myStack; /* For integer stack*/
2 stack <float > myStack; /* For float stack*/
stack <string > myStack; /* For string stack*/
✌
✆
Stack is based on the Last In First Out (LIFO) principle. The last element inserted by
push() function returns at first by pop() function.
3.5.1 Empty Stack
empty() function tells whether a stack is empty or non empty. If stack is empty then it
returns true otherwise returns false.
✞
1 #include <iostream >
#include <stack >
3 using namespace std;
5 int main (int argc , char ** argv ) {
stack <int > myStack;
7 myStack .push (10) ;
cout << myStack.empty() << endl ; /* Returns 0*/
9 myStack .pop();
cout << myStack.empty() << endl ; /* Returns 1*/
11 return 0;
}
✌
✆
✞
0
1
✌
✆
3.5.2 Size of Stack
size() function returns the size of the stack.
✞
#include <iostream >
2 #include <stack >
using namespace std;
4
int main (int argc , char ** argv ) {
6 stack <int > myStack;
myStack .push (10) ;
8 myStack .push (11) ;
myStack .push (12) ;
10 cout << "Size of stack : ";
cout << myStack.size () << endl ; /* Returns 3*/
12 myStack .pop();
248 Accessing System Files
cout << "Size of stack : ";
14 cout << myStack.size () << endl ; /* Returns 2*/
return 0;
16 }
✌
✆
✞
Size of stack : 3
Size of stack : 2
✌
✆
3.5.3 Get Top Element
top() returns the reference of topmost element of the stack. This function can replace the
top most element or can do arithmetic on it if arithmetic operator is used.
✞
#include <iostream >
2 #include <stack >
using namespace std;
4
int main (int argc , char ** argv ) {
6 stack <int > myStack;
myStack .push (10) ;
8 myStack .push (11) ;
myStack .push (12) ;
10 cout << "Size of stack before top () is : ";
cout << myStack.size () << endl ; /* Returns 3*/
12 myStack .top() = 10;
cout << "Size of stack after top () is : ";
14 cout << myStack.size () << endl ;/* Returns 3*/
cout << "Top stack is : ";
16 cout << myStack.top () << endl ; /* Returns 10*/
myStack .top() -= 7;
18 cout << "Top stack is : ";
cout << myStack.top () << endl ; /* Returns 3*/
20 return 0;
}
✌
✆
✞
Size of stack before top () is : 3
Size of stack after top () is : 3
Top stack is : 10
Top stack is : 3
✌
✆
3.5.4 Add Element at Top
push function is used to add an element into the stack. Its syntax is
✞
<stack name >. push (<value >);
✌
✆
3.5. STACK 249
✞
1 #include <iostream >
#include <stack >
3 using namespace std;
5 int main (int argc , char ** argv ) {
stack <int > myStack;
7 myStack .push (10) ;
myStack .push (11) ;
9 myStack .push (12) ;
cout << "Top element is : ";
11 cout << myStack.top () << endl ; /* Returns 12*/
return 0;
13 }
✌
✆
✞
Top element is : 12
✌
✆
3.5.5 Remove Top Element
pop is used to remove the top of the element of a stack. It is used as
✞
1 <stack name >. pop();
✌
✆
✞
1 #include <iostream >
#include <stack >
3 using namespace std;
5 int main (int argc , char ** argv ) {
stack <int > myStack;
7 myStack .push (10) ;
myStack .push (11) ;
9 myStack .push (12) ;
cout << "Top element is : ";
11 cout << myStack.top () << endl ; /* Returns 12*/
myStack .pop(); /* Remove top most element */
13 cout << "Top element is : ";
cout << myStack.top () << endl ; /* Returns 11*/
15 return 0;
}
✌
✆
✞
Top element is : 12
Top element is : 11
✌
✆
250 OOP in C++
4.1. STRUCTURES 251
4OOP in C++
4.1 Structures
In Object Oriented Programming, a structure is required. A struct is like a class except
for the default access. C++ also support the C like structure. Structures are also allow
Operator Overloading. A struct is defined as
✞
struct myStructType /*: inheritances */ {
2 public:
<public memters >
4 protected :
<protected members >
6 private :
<private members >
8 } myStructName ;
✌
✆
public members are accessed from anywhere by declaring structure object and calling
public member. private members are accessed within the structure definition only, i.e.
by member classes or member functions defined within the parent structure. protected
members are accessible in the class or through derived classes. An object of type ‘myS-
tructType’ is declared as
✞
myStructType <object name >;
✌
✆
The simplest example of the struct is the structure for the coordinate point. A point
structure is defined and initialized as
✞
1 struct Point {
double x, y;
3 };
✌
✆
In this definition of structure, there are two members named as x and y. We can set the
values to the member of this structure as
✞
1 struct Point blank;
blank.x = 3.0;
3 blank.y = 4.0;
✌
✆
We can read the values of an instance variable using the same syntax we used to write
them:
✞
1 int x = blank.x;
✌
✆
See the example below:
252 OOP in C++
✞
1 #include <iostream >
using namespace std;
3
struct Point {
5 double x, y;
};
7
int main (int argc , char *argv []) {
9 struct Point point;
point.x = 1;
11 point.y = 1.5;
cout << "x is " << point.x << " and y is " << point.y;
13 return 0;
}
✌
✆
✞
x is 1 and y is 1.5
✌
✆
The detailed explanation is given in struct section. Size of struct is equal to the sum of
sizes of its all variables.
✞
1 #include <iostream >
using namespace std;
3
struct A {
5 int i [30]; /*30 X 4= 120 bytes*/
int j [20]; /*20 X 4= 80 bytes*/
7 };/* Total size is 200 bytes*/
9 int main (int argc , char *argv []) {
cout << "sizeof struct A = " << sizeof (A)
11 << " bytes" << endl ;
return 0;
13 }
✌
✆
✞
sizeof struct A = 200 bytes
✌
✆
struct can also holds the member function inside them. A member function inside the
struct is modified by using operator ‘::’. The member function is accessed by calling struct
and its member function. See the example below:
✞
1 #include <iostream >
using namespace std;
3
struct A {
5 void g();/* declaring member function */
};
7
/* Accessing the member function g()*
9 *of structure A and modifing to it*/
4.1. STRUCTURES 253
void A::g() {
11 cout << "Sturcture A" << endl ;
}
13
int main (int argc , char *argv []) {
15 /* Declare and initialized struct A*/
struct A a;
17 /* Call to memeber function g()*/
a.g();
19 return 0;
}
✌
✆
✞
Sturcture A
✌
✆
Pointer can also be used in argument of a member function. A child structure alongwith
its members can also be defined inside the parent structure. See the example below:
✞
1 #include <iostream >
using namespace std;
3
struct A {
5 /* declaring member function *
*with pointer type argument */
7 void g(int* x);
9 struct B {
void h();
11 };
};
13
/* Accessing the member function g()*
15 *of structure A and modifing to it*/
void A::g(int* x) {
17 cout << "Sturcture A" << endl ;
cout << "x is " << *x << endl ;
19 }
21 void A::B::h() {
cout << "Nested struct !!";
23 }
25 int main (int argc , char *argv []) {
struct A a;
27 int i = 12;
a.g(&i);
29 struct A::B b;
b.h();
31 return 0;
}
✌
✆
254 OOP in C++
✞
Sturcture A
x is 12
Sturcture A
x is -12
✌
✆
Following example has a nested struct model. The nested model has member function
h(). Function definition of this member function is defined outside the structure by using
operator ‘::’.
✞
#include <iostream >
2 using namespace std;
4 /* Outer parent structure */
struct A {
6 void g(int* x);
8 /* Nested child structure */
struct B {
10 void h();
};
12 };
14 void A::g(int* x) {
cout << "Sturcture A" << endl ;
16 cout << "x is " << *x << endl ;
}
18
/* Accessing function of nested child B *
20 *structure and defining its definitions .*/
void A::B::h() {
22 cout << "Nested struct !!";
}
24
int main (int argc , char *argv []) {
26 struct A a;
int i = 12;
28 a.g(&i);
struct A::B b;
30 b.h();
return 0;
32 }
✌
✆
✞
Sturcture A
x is 12
Nested struct !!
✌
✆
4.2. CLASSES 255
4.2 Classes
Classes are used to create user defined types which includes the set of functions. An
instance of a class is called an object and programs can contain any number of classes.
As with other types, object types are case-sensitive. A class can have both, the data
members and the function members associated with it. A class is defined by:
✞
1 class MyClass {
/* public , protected and private *
3 * variables /constants /functions */
};
✌
✆
An object of MyClass class is declared as shown in the following syntax.
✞
MyClass object;
✌
✆
By default, all class members are initially private unless they are declared as pro-
tected or public. A class is like a container which contains is all members.
✞
1 class MyClass {
int x;// integer variable x
3 void f(){}// function with definition
};
✌
✆
MyClass
x void f()
Figure 4.1: Fields/Members of a class.
Remember that the memory arrangement of the class object is in different form. Non-
virtual functions do not reflects in memory arrangement. (See Virtual Function Table
(VFT) for details.) The object of a class can not access to private data members of own
class but they can be accessed from within the class.
✞
#include <iostream >
2 using namespace std;
4 class A {
int x = 1;
6 public:
int y = 2;
8 void X(){
256 OOP in C++
cout << x << endl ;
10 }
};
12
int main () {
14 A *a = new A();
// cout << a->x;// Error!! accessing private member
16 cout << a->y << endl ;
a->X(); // Return the value of private A::x
18 return 0;
}
✌
✆
✞
2
1
✌
✆
A
x=1 y=2 X()
a (object of A)
x=1 y=2 X()
In first part of above figure, all data members of the class ‘A’ are shown. In second part
of above figure, object of class ‘A’ can not access private member ‘x’ directly but it can
access to it via member function ‘X()’. If object of a class is declared twice then each
object is created at different location of memory address. See in the example given below:
✞
#include <iostream >
2 using namespace std;
4 class Address {
int HNo;
6 int BlockNo ;
public:
8 void getLocality ();
void getDistrict ();
10 void getState ();
int pin;
12 };
14 int main () {
Address A, B;
16 cout << "Memory Address of object A is " << &A << endl ;
cout << "Memory Address of object B is " << &B << endl ;
18 return 0;
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2

More Related Content

What's hot (20)

C tech questions
C tech questionsC tech questions
C tech questions
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2
 
C++ Pointers
C++ PointersC++ Pointers
C++ Pointers
 
Fp201 unit5 1
Fp201 unit5 1Fp201 unit5 1
Fp201 unit5 1
 
C++ L05-Functions
C++ L05-FunctionsC++ L05-Functions
C++ L05-Functions
 
C++ L07-Struct
C++ L07-StructC++ L07-Struct
C++ L07-Struct
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.
 
C++ L06-Pointers
C++ L06-PointersC++ L06-Pointers
C++ L06-Pointers
 
Stl algorithm-Basic types
Stl algorithm-Basic typesStl algorithm-Basic types
Stl algorithm-Basic types
 
C++ L04-Array+String
C++ L04-Array+StringC++ L04-Array+String
C++ L04-Array+String
 
Container adapters
Container adaptersContainer adapters
Container adapters
 
C++ Programming - 11th Study
C++ Programming - 11th StudyC++ Programming - 11th Study
C++ Programming - 11th Study
 
C aptitude scribd
C aptitude scribdC aptitude scribd
C aptitude scribd
 
C++ L03-Control Structure
C++ L03-Control StructureC++ L03-Control Structure
C++ L03-Control Structure
 
Array notes
Array notesArray notes
Array notes
 
Static and const members
Static and const membersStatic and const members
Static and const members
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Implementing stack
Implementing stackImplementing stack
Implementing stack
 
Inheritance and polymorphism
Inheritance and polymorphismInheritance and polymorphism
Inheritance and polymorphism
 
C++ L01-Variables
C++ L01-VariablesC++ L01-Variables
C++ L01-Variables
 

Similar to Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2

C++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfC++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfyamew16788
 
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...GkhanGirgin3
 
Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++NUST Stuff
 
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 ProcessingMeghaj Mallick
 
a) Write the recursive function in C++ to sort a set of data using M.pdf
a) Write the recursive function in C++ to sort a set of data using M.pdfa) Write the recursive function in C++ to sort a set of data using M.pdf
a) Write the recursive function in C++ to sort a set of data using M.pdfnageswara1958
 
Oops lab manual2
Oops lab manual2Oops lab manual2
Oops lab manual2Mouna Guru
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptxNelyJay
 
#include stdafx.h using namespace std; #include stdlib.h.docx
#include stdafx.h using namespace std; #include stdlib.h.docx#include stdafx.h using namespace std; #include stdlib.h.docx
#include stdafx.h using namespace std; #include stdlib.h.docxajoy21
 
c++ practical Digvajiya collage Rajnandgaon
c++ practical  Digvajiya collage Rajnandgaonc++ practical  Digvajiya collage Rajnandgaon
c++ practical Digvajiya collage Rajnandgaonyash production
 
SP-First-Lecture.ppt
SP-First-Lecture.pptSP-First-Lecture.ppt
SP-First-Lecture.pptFareedIhsas
 

Similar to Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2 (20)

C++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfC++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdf
 
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
 
Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++
 
Arrays
ArraysArrays
Arrays
 
C++ practical
C++ practicalC++ practical
C++ practical
 
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
 
a) Write the recursive function in C++ to sort a set of data using M.pdf
a) Write the recursive function in C++ to sort a set of data using M.pdfa) Write the recursive function in C++ to sort a set of data using M.pdf
a) Write the recursive function in C++ to sort a set of data using M.pdf
 
Oops lab manual2
Oops lab manual2Oops lab manual2
Oops lab manual2
 
2- Dimensional Arrays
2- Dimensional Arrays2- Dimensional Arrays
2- Dimensional Arrays
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptx
 
Lab 13
Lab 13Lab 13
Lab 13
 
C++ file
C++ fileC++ file
C++ file
 
C++ file
C++ fileC++ file
C++ file
 
#include stdafx.h using namespace std; #include stdlib.h.docx
#include stdafx.h using namespace std; #include stdlib.h.docx#include stdafx.h using namespace std; #include stdlib.h.docx
#include stdafx.h using namespace std; #include stdlib.h.docx
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Computer Programming- Lecture 9
Computer Programming- Lecture 9Computer Programming- Lecture 9
Computer Programming- Lecture 9
 
c++ practical Digvajiya collage Rajnandgaon
c++ practical  Digvajiya collage Rajnandgaonc++ practical  Digvajiya collage Rajnandgaon
c++ practical Digvajiya collage Rajnandgaon
 
SP-First-Lecture.ppt
SP-First-Lecture.pptSP-First-Lecture.ppt
SP-First-Lecture.ppt
 
C++ TUTORIAL 5
C++ TUTORIAL 5C++ TUTORIAL 5
C++ TUTORIAL 5
 
pointers
pointerspointers
pointers
 

More from ssuserd6b1fd

Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...
Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...
Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...ssuserd6b1fd
 
Decreasing increasing functions by arun umrao
Decreasing increasing functions by arun umraoDecreasing increasing functions by arun umrao
Decreasing increasing functions by arun umraossuserd6b1fd
 
Distribution of normal data understanding it numerical way by arun umrao
Distribution of normal data   understanding it numerical way by arun umraoDistribution of normal data   understanding it numerical way by arun umrao
Distribution of normal data understanding it numerical way by arun umraossuserd6b1fd
 
Decreasing and increasing functions by arun umrao
Decreasing and increasing functions by arun umraoDecreasing and increasing functions by arun umrao
Decreasing and increasing functions by arun umraossuserd6b1fd
 
What is meaning of epsilon and delta in limits of a function by Arun Umrao
What is meaning of epsilon and delta in limits of a function by Arun UmraoWhat is meaning of epsilon and delta in limits of a function by Arun Umrao
What is meaning of epsilon and delta in limits of a function by Arun Umraossuserd6b1fd
 
Notes for GNU Octave - Numerical Programming - for Students 01 of 02 by Arun ...
Notes for GNU Octave - Numerical Programming - for Students 01 of 02 by Arun ...Notes for GNU Octave - Numerical Programming - for Students 01 of 02 by Arun ...
Notes for GNU Octave - Numerical Programming - for Students 01 of 02 by Arun ...ssuserd6b1fd
 
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 ...ssuserd6b1fd
 
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...ssuserd6b1fd
 
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...ssuserd6b1fd
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...ssuserd6b1fd
 
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...ssuserd6b1fd
 
Work and Energy Notes by Arun Umrao
Work and Energy Notes by Arun UmraoWork and Energy Notes by Arun Umrao
Work and Energy Notes by Arun Umraossuserd6b1fd
 
Notes of Units, Dimensions & Errors for IIT JEE by Arun Umrao
Notes of Units, Dimensions & Errors for IIT JEE by Arun UmraoNotes of Units, Dimensions & Errors for IIT JEE by Arun Umrao
Notes of Units, Dimensions & Errors for IIT JEE by Arun Umraossuserd6b1fd
 
Physics dictionary for CBSE, ISCE, Class X Students by Arun Umrao
Physics dictionary for CBSE, ISCE, Class X Students by Arun UmraoPhysics dictionary for CBSE, ISCE, Class X Students by Arun Umrao
Physics dictionary for CBSE, ISCE, Class X Students by Arun Umraossuserd6b1fd
 
Java Programming Notes for Beginners by Arun Umrao
Java Programming Notes for Beginners by Arun UmraoJava Programming Notes for Beginners by Arun Umrao
Java Programming Notes for Beginners by Arun Umraossuserd6b1fd
 
Notes of 8085 micro processor Programming for BCA, MCA, MSC (CS), MSC (IT) &...
Notes of 8085 micro processor Programming  for BCA, MCA, MSC (CS), MSC (IT) &...Notes of 8085 micro processor Programming  for BCA, MCA, MSC (CS), MSC (IT) &...
Notes of 8085 micro processor Programming for BCA, MCA, MSC (CS), MSC (IT) &...ssuserd6b1fd
 
Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...
Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...
Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...ssuserd6b1fd
 
Modlica an introduction by Arun Umrao
Modlica an introduction by Arun UmraoModlica an introduction by Arun Umrao
Modlica an introduction by Arun Umraossuserd6b1fd
 
Maxima CAS an introduction
Maxima CAS an introductionMaxima CAS an introduction
Maxima CAS an introductionssuserd6b1fd
 
Maxima & Minima of Functions - Differential Calculus by Arun Umrao
Maxima & Minima of Functions - Differential Calculus by Arun UmraoMaxima & Minima of Functions - Differential Calculus by Arun Umrao
Maxima & Minima of Functions - Differential Calculus by Arun Umraossuserd6b1fd
 

More from ssuserd6b1fd (20)

Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...
Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...
Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...
 
Decreasing increasing functions by arun umrao
Decreasing increasing functions by arun umraoDecreasing increasing functions by arun umrao
Decreasing increasing functions by arun umrao
 
Distribution of normal data understanding it numerical way by arun umrao
Distribution of normal data   understanding it numerical way by arun umraoDistribution of normal data   understanding it numerical way by arun umrao
Distribution of normal data understanding it numerical way by arun umrao
 
Decreasing and increasing functions by arun umrao
Decreasing and increasing functions by arun umraoDecreasing and increasing functions by arun umrao
Decreasing and increasing functions by arun umrao
 
What is meaning of epsilon and delta in limits of a function by Arun Umrao
What is meaning of epsilon and delta in limits of a function by Arun UmraoWhat is meaning of epsilon and delta in limits of a function by Arun Umrao
What is meaning of epsilon and delta in limits of a function by Arun Umrao
 
Notes for GNU Octave - Numerical Programming - for Students 01 of 02 by Arun ...
Notes for GNU Octave - Numerical Programming - for Students 01 of 02 by Arun ...Notes for GNU Octave - Numerical Programming - for Students 01 of 02 by Arun ...
Notes for GNU Octave - Numerical Programming - for Students 01 of 02 by Arun ...
 
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 ...
 
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
 
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...
 
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...
Notes and Description for Xcos Scilab Block Simulation with Suitable Examples...
 
Work and Energy Notes by Arun Umrao
Work and Energy Notes by Arun UmraoWork and Energy Notes by Arun Umrao
Work and Energy Notes by Arun Umrao
 
Notes of Units, Dimensions & Errors for IIT JEE by Arun Umrao
Notes of Units, Dimensions & Errors for IIT JEE by Arun UmraoNotes of Units, Dimensions & Errors for IIT JEE by Arun Umrao
Notes of Units, Dimensions & Errors for IIT JEE by Arun Umrao
 
Physics dictionary for CBSE, ISCE, Class X Students by Arun Umrao
Physics dictionary for CBSE, ISCE, Class X Students by Arun UmraoPhysics dictionary for CBSE, ISCE, Class X Students by Arun Umrao
Physics dictionary for CBSE, ISCE, Class X Students by Arun Umrao
 
Java Programming Notes for Beginners by Arun Umrao
Java Programming Notes for Beginners by Arun UmraoJava Programming Notes for Beginners by Arun Umrao
Java Programming Notes for Beginners by Arun Umrao
 
Notes of 8085 micro processor Programming for BCA, MCA, MSC (CS), MSC (IT) &...
Notes of 8085 micro processor Programming  for BCA, MCA, MSC (CS), MSC (IT) &...Notes of 8085 micro processor Programming  for BCA, MCA, MSC (CS), MSC (IT) &...
Notes of 8085 micro processor Programming for BCA, MCA, MSC (CS), MSC (IT) &...
 
Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...
Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...
Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...
 
Modlica an introduction by Arun Umrao
Modlica an introduction by Arun UmraoModlica an introduction by Arun Umrao
Modlica an introduction by Arun Umrao
 
Maxima CAS an introduction
Maxima CAS an introductionMaxima CAS an introduction
Maxima CAS an introduction
 
Maxima & Minima of Functions - Differential Calculus by Arun Umrao
Maxima & Minima of Functions - Differential Calculus by Arun UmraoMaxima & Minima of Functions - Differential Calculus by Arun Umrao
Maxima & Minima of Functions - Differential Calculus by Arun Umrao
 

Recently uploaded

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
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
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
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
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
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
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
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 

Recently uploaded (20)

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
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
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...
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
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
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
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🔝
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 

Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and MSC (CS) by Arun Umrao 2 of 2

  • 1. 1.11. MATHEMATICS 181 24 return 0; } ✌ ✆ Output of above program is ✞ Addition of 5 and 2 is : 7 Subtraction of 5 and 2 is : 3 Multiplication of 5 and 2 is : 10 Division of 5 and 2 is : 2 Modulus of 5 and 2 is : 1 ✌ ✆ If mathematical expressions are mixed with C++ operators and are directly made to be put at output stream then their grouping is required. Parentheses are used to group the scope of expression. ✞ 1 #include <iostream > using namespace std; 3 int main (int argc , char ** argv ) { 5 /*3 + 3 << 1 * * 6 << 1 * 7 * 6 1 */ /* Here << is considered as a * 9 *C++ insertion operator */ cout << 3 + 3 << 1 << endl ; 11 /*(3 + 3 << 1)* * (6 << 1) * 13 * 12 */ /* Here << is considered as* 15 *a left shift operator */ cout << (3 + 3 << 1) << endl ; 17 return 0; } ✌ ✆ ✞ 61 12 ✌ ✆
  • 2. 182 Array & Pointer
  • 3. 2.1. ARRAY 183 2Array & Pointer 2.1 Array Arrays in C++ stores data in a single variable name with an index, also known as a subscript. It is simply a list or ordered grouping for variables of the same type. Arrays often help a programmer in organize collections of data efficiently and intuitively. 2.1.1 Uni-dimensional Array Arrays are declared and initialized like ✞ int numbers [6]; // array declared 2 int point [6]={0 , 0, 1, 0, 0, 0}; // array initialized ✌ ✆ The brackets ‘[ ]’ identify ‘numbers’ or ‘points’ and the number enclosed in the bracket indicates the number of elements in the array, i.e. subscripts of the array. An element of array can be accessed by its index number. In following example, each element of the array is accessed by its index number. ✞ #include <iostream > 2 using namespace std; 4 int main (int argc , char ** argv ) { int ix; 6 short anArray [] = {3, 6, 9, 12, 15}; for (ix = 0; ix < ( sizeof (anArray ) / sizeof ( short)); ++ix) { 8 cout << anArray [ix] << endl ; } 10 return 0; } ✌ ✆ In the above example, size of array was not explicitly specified. The compiler knows size of array from the initialized list. The size of ‘anArray’ is ‘5’ because ‘anArray’ has five elements. Addition of an additional element to the list will increase its size to six. Static declaration of the size of an array, the array list will be overflow. To overcome this problem sizeof expression is used as ✞ 1 size = sizeof(anArray)/ sizeof(short) ✌ ✆ Because of the sizeof expression in for loop, the script is automatically adjusted to this change. Designated initializer is allow to pick and choose the initialized elements. An array initialised with ‘[ ]’ is called expandable array. When an array is declared without
  • 4. 184 Array & Pointer its size, compiler first counts elements of the array and then it grows the array upto a size so that all the elements can be stored in the array. ✞ 1 /* Array with growing size . */ int days [] = {31, 28, 31, 30, 31, 29}; ✌ ✆ A one dimensional array with variable size can not be declared as shown below: ✞ int i; 2 cin >> i; int a[i] ✌ ✆ The size must be constant. Again, if the array is created with variable size using new keyword, then it is acceptable. ✞ 1 #include <iostream > using namespace std; 3 int main () { 5 int n, j; cout << "How may array size : "; 7 cin >> n; /* Reserve the memory */ 9 int *a = new int[n]; for (j = 0; j < n; j++) { 11 a[j] = j*n; } 13 for (j = 0; j < n; j++) { cout << a[j] << endl ; 15 } delete [] a;// Free the memory , required compulsory 17 return 0; } ✌ ✆ ✞ 0 3 6 ✌ ✆ 2.1.2 Multi-dimensional Array A multi-dimensional array can be declared and initialized as given below: ✞ 1 int two_d [2][3] = {{ 5, 2, 1 }, { 6, 7, 8 }}; ✌ ✆ Here [2] represents number of rows and [3] represents number of columns of the two dimensional array. Multi-dimensional array can be used to add, subtract and product (either dot or cross) of two vectors or matrices.
  • 5. 2.1. ARRAY 185 ✞ #include <iostream > 2 using namespace std; 4 #define X 5 #define Y 5 6 int main (int argc , char ** argv ) { 8 int ix , iy; 10 short anArray[X][Y]; for (ix = 0; ix < X; ++ix) { 12 for (iy = 0; iy < Y; ++iy) { anArray[ix][ iy] = ix * iy; 14 }; } 16 for (ix = 0; ix < X; ++ix) { for (iy = 0; iy < Y; ++iy) { 18 cout << anArray [ix][iy] << "t"; }; 20 cout << endl ; } 22 return 0; } ✌ ✆ ✞ 0 0 0 0 0 0 1 2 3 4 0 2 4 6 8 0 3 6 9 12 0 4 8 12 16 ✌ ✆ Following is an example of elementwise addition and subtraction of two matrices. ✞ 1 #include <iostream > using namespace std; 3 /* Random number generator between 0 to 10.*/ 5 int rand_num (int a, int b) { return ((a * 97 + b * 21) & 10); 7 } 9 int main (int argc , char ** argv ) { int i/* row*/, 11 j/* col*/; int A [3][3]/* First Matrix*/, 13 B[3][3]/* Second Matrix*/ , C[3][3]/* Dot Matrix*/; 15 cout << "First Random Matrix is :" << endl ; /* For each of three rows */ 17 for (i = 0; i < 3; i++) { /* There are three columns.*/
  • 6. 186 Array & Pointer 19 for (j = 0; j < 3; j++) { /* Assign a random matrix elements .*/ 21 A[i][j] = rand_num (i*j, j); cout << A[i][j] << "t"; 23 } /* Print new line after completion of each row*/ 25 cout << endl << endl ; } 27 cout << "Second Random Matrix is :" << endl ; /* For each of three rows */ 29 for (i = 0; i < 3; i++) { /* There are three columns.*/ 31 for (j = 0; j < 3; j++) { /* Assign a random matrix elements .*/ 33 B[i][j] = rand_num (i, i * j); cout << B[i][j] << "t"; 35 } /* Print new line after completion of each row*/ 37 cout << endl << endl ; } 39 cout << "Elementwise Addition of Matrices is :" << endl ; /* For each of three rows */ 41 for (i = 0; i < 3; i++) { /* There are three columns.*/ 43 for (j = 0; j < 3; j++) { /* Add matrices elementwise .*/ 45 C[i][j] = A[i][j] + B[i][j]; cout << C[i][j] << "t"; 47 } /* Print new line after completion of each row*/ 49 cout << endl << endl ; } 51 cout << "Elementwise Subtraction of Matrices is :" << endl ; /* For each of three rows */ 53 for (i = 0; i < 3; i++) { /* There are three columns.*/ 55 for (j = 0; j < 3; j++) { /* Subtract matrices elementwise .*/ 57 C[i][j] = A[i][j] - B[i][j]; cout << C[i][j] << "t"; 59 } /* Print new line after completion of each row*/ 61 cout << endl << endl ; } 63 return 0; } ✌ ✆ ✞ First Random Matrix is : 0 0 10 0 2 8 0 2 10
  • 7. 2.1. ARRAY 187 Second Random Matrix is : 0 0 0 0 2 10 2 8 2 Elementwise Addition of Matrix is : 0 0 10 0 4 18 2 10 12 Elementwise Subtraction of Matrix is : 0 0 10 0 0 -2 -2 -6 8 ✌ ✆ Dot product example is ✞ #include <iostream > 2 using namespace std; 4 /* Random number generator between 0 to 10.*/ int rand_num (int a, int b) { 6 return ((a * 97 + b * 21) & 10); } 8 int main (int argc , char ** argv ) { 10 int i/* row*/, j/* col*/; 12 int A [3][3]/* First Matrix*/, B[3][3]/* Second Matrix*/ , 14 C[3][3]/* Dot Matrix*/; cout << "First Random Matrix is :" << endl ; 16 /* For each of three rows */ for (i = 0; i < 3; i++) { 18 /* There are three columns.*/ for (j = 0; j < 3; j++) { 20 /* Assign a random matrix elements .*/ A[i][j] = rand_num (i*j, j); 22 cout << A[i][j] << "t"; } 24 /* Print new line after completion of each row*/ cout << endl << endl ; 26 } cout << "Second Random Matrix is :" << endl ; 28 /* For each of three rows */ for (i = 0; i < 3; i++) { 30 /* There are three columns.*/ for (j = 0; j < 3; j++) { 32 /* Assign a random matrix elements .*/ B[i][j] = rand_num (i, i * j); 34 cout << B[i][j] << "t"; } 36 /* Print new line after completion of each row*/ cout << endl << endl ;
  • 8. 188 Array & Pointer 38 } cout << "Dot Product of Matrices is :" << endl ; 40 /* For each of three rows */ for (i = 0; i < 3; i++) { 42 /* There are three columns.*/ for (j = 0; j < 3; j++) { 44 /* Subtract matrices elementwise .*/ C[i][j] = A[i][j] * B[i][j]; 46 cout << C[i][j] << "t"; } 48 /* Print new line after completion of each row*/ cout << endl << endl ; 50 } return 0; 52 } ✌ ✆ ✞ First Random Matrix is : 8 2 2 2 2 0 2 0 8 Second Random Matrix is : 8 8 8 8 2 2 8 2 8 Dot Product Matrix is : 64 16 16 16 4 0 16 0 64 ✌ ✆ Cross product example is ✞ #include <iostream > 2 #include <cmath > using namespace std; 4 /* Random number generator between 0 to 10.*/ 6 int newseed = 10; 8 int seed (int a) { newseed = newseed + a; 10 return newseed; } 12 int rand_num (int a) { 14 seed (a); return (( newseed * 99991 + 12345) & 10); 16 } 18 int main (int argc , char ** argv ) { int i/* row*/, 20 j/* col*/;
  • 9. 2.1. ARRAY 189 int A[3]/* First Matrix */, 22 B[3]/* Second Matrix*/, C[3]/* Vector Matrix*/; 24 cout << "First Random Matrix is :" << endl ; /* For each of three rows */ 26 for (i = 0; i < 3; i++) { /* There are three columns.*/ 28 /* Assign a random matrix elements .*/ A[i] = rand_num (i); 30 cout << A[i] << "t"; } 32 cout << endl ; cout << "Second Random Matrix is :" << endl ; 34 /* For each of three rows */ for (i = 0; i < 3; i++) { 36 /* There are three columns.*/ /* Assign a random matrix elements .*/ 38 B[i] = rand_num (i); cout << B[i] << "t"; 40 } cout << endl ; 42 cout << "Cross Product of Matrices is :" << endl ; 44 /* For each of three rows */ for (i = 0; i < 3; i++) { 46 /* Subtract matrices elementwise .*/ C[i] = pow(-1, 2 * i)* (A[(i + 1) % 3] * B[(i + 2) % 3] 48 - B[(i + 1) % 3] * A[(i + 2) % 3]); cout << C[i] << "t"; 50 } return 0; 52 } ✌ ✆ ✞ First Random Vector is : 10 2 0 Second Random Vector is : 0 10 8 Cross Product Vector is : 16 -80 100 ✌ ✆ Array can be passed to a function like ✞ #include <iostream > 2 using namespace std; 4 /*+- Array pointer with ** **| expandable size */ 6 void init_array (int a[], int count) { int i; 8 for (i = 0; i < count; i++) a[i] = i * 10;
  • 10. 190 Array & Pointer 10 for (i = 0; i < count; i++) cout << "The a value is " << a[i] << endl ; 12 } 14 int main (int argc , char ** argv ) { int mydata [10]; 16 init_array (mydata , 5); return 0; 18 } ✌ ✆ ✞ The a value is 0. The a value is 10. The a value is 20. The a value is 30. The a value is 40. ✌ ✆ For multidimensional array, there is no limit of dimension in C. Here, a four dimensional matrix is represented by ✞ 1 int myData [2][3][2][4] ✌ ✆ A new dimension in array declaration is always grouped by curly braces. One dimensional array has one curly braces, i.e. one row. In two dimensional array, there are two one dimensional rows both separated by comma (,) operator. These two rows are enclosed by another curly braces. In three dimensional systems of arrays, two 2-dimensional arrays are placed one over another. In the following example, two, three and four dimensional arrays are declared. ✞ 1 #include <iostream > using namespace std; 3 int main (int argc , char ** argv ) { 5 int a [2][2] = { // cols 7 {1, 2}, // row {5, 6} // row 9 }; int b [2][2][2] = { 11 { // cols 13 {1, 2}, // row {5, 6} // row 15 }, {// height 17 {4, 3}, {8, 9} 19 } }; 21 int c [2][2][2][2] = { {
  • 11. 2.1. ARRAY 191 23 { // cols 25 {1, 2}, // row {5, 6} // row 27 }, {// height 29 {1, 2}, {5, 6} 31 } }, 33 {// time { 35 {4, 1}, {7, 6} 37 }, { 39 {4, 4}, {9, 1} 41 } } 43 }; int i, j, k, l; 45 cout << "Elements of matrix a are " << endl ; for (i = 0; i < 2; i++) { 47 for (j = 0; j < 2; j++) { cout << "Element " << a[i][j] << endl ; 49 } } 51 cout << "Elements of matrix b are " << endl ; for (i = 0; i < 2; i++) { 53 for (j = 0; j < 2; j++) { for (k = 0; k < 2; k++) { 55 cout << "Element " << b[i][j][k] << endl ; } 57 } } 59 cout << "Elements of matrix c are " << endl ; for (i = 0; i < 2; i++) { 61 for (j = 0; j < 2; j++) { for (k = 0; k < 2; k++) { 63 for (l = 0; l < 2; l++) { cout << "Element " << c[i][j][k][l] << endl ; 65 } } 67 } } 69 return 0; } ✌ ✆
  • 12. 192 Array & Pointer 2.1.3 Array in Function In a function, an argument is passed as value unless the program needs to alter the argument. In this case there is requirement that a pointer should be passed to the function. Arrays can passed to a function as pointers. If an array is passed to the function, function would have to allocate enough space to hold a copy of the original array and then copy all the data from the original array to the new array. It is much quicker to pass the address of the array rather than array itself and have the function work with the original data. Prototype for the passing of an array to the function is ✞ int sum(int arr []) ✌ ✆ C++ compilers do not check the size of the array passed to the function hence for good programming, the function should know the limits of actions on the array. This is why a new parameter of array size as ‘n’ is passed to the function as ✞ 1 int sum(int arr[], int n) ✌ ✆ The name of an array is address of first element hence array name passed as argument to the function should be matching argument and a pointer. In this context int arr[] is same as the int * arr. In case of multi-dimensional array, first bracket in the multidimensional array may be empty or not empty but other bracket should contains a valid integer for the size of the array dimension. ✞ 1 #include <iostream > using namespace std; 3 #define ROWS 3 #define COLS 4 5 int sum(int rows , int cols , int ar [][ COLS ]); 7 int main (void ) { int i, j; 9 int varr [ROWS ][ COLS ]; for (i = 0; i < ROWS ; i++) 11 for (j = 0; j < COLS ; j++) varr [i][j] = i * j + j; 13 cout << "3x4 Array n"; cout << "Sum of all elements " << sum(ROWS , COLS , varr ); 15 return 0; } 17 int sum(int rows , int cols , int ar [][ COLS ]) { 19 int r; int c; 21 int tot = 0; for (r = 0; r < rows ; r++) 23 for (c = 0; c < cols ; c++) tot += ar[r][c]; 25 return tot; } ✌ ✆
  • 13. 2.1. ARRAY 193 ✞ 3x4 Array Sum of all elements 36 ✌ ✆ 2.1.4 Return Array From Function C++ allows to return an array from a function. To return single dimension array, we create a function with pointer. See the example below: ✞ #include <iostream > 2 #include <ctime > using namespace std; 4 int * getArray () { 6 static int a[5]; 8 for (int i = 0; i < 5; ++i) { a[i] = i * 2; 10 } return a; 12 } 14 int main (int argc , char *argv []) { int *p; 16 p = getArray (); 18 for (int i = 0; i < 5; i++) { 20 cout << "*(p + " << i << ") : "; cout << *(p + i) << endl ; 22 } 24 return 0; } ✌ ✆ ✞ *(p + 0) : 0 *(p + 1) : 2 *(p + 2) : 4 *(p + 3) : 6 *(p + 4) : 8 ✌ ✆ 2.1.5 String As Array String is defined as array of characters. C++ allows a character array to be represented by a character string with a null terminating character which is automatically added at the end of character array instead of a list of characters. Example of string array is shown below.
  • 14. 194 Array & Pointer ✞ 1 char string [] = {’A’, ’p’, ’p’, ’l’, ’e’, ’S’, ’0 ’}; ✌ ✆ Normal size of a string array is controlled at initialization of the string array. An string array stores elements upto its declared length. Excess elements are ignored and skipped. In following example only ten characters will be stored in the string array ‘mystr’. ✞ 1 char mystr [10] = "Apple is red."; ✌ ✆ It is convenient to let the compiler determine the array size. If anyone omits the size of array at the time of array declaration and initialization, the compiler itself determines the size for supplied string. In following example, compiler set the string length of thirteen characters. ✞ 1 char mystr[] = "Apple is red."; ✌ ✆ A pointer-to-string method may also be used for string declaration and initialization. In pointer notation, above example will be looked like ✞ 1 const char *ptrstr = "Merkkijono "; ✌ ✆ Both declarations amount to saying that ‘ptrstr’ is a pointer to the indicated string. ‘ptrstr’ string variable declared as array or as pointer, both are same but only pointer version can be used with increment operator. To create an extra long string, string is splitted into multiple sections, by closing the first section with a quote, and recommencing the string on the next line (also starting and ending in a quote): ✞ 1 char string [] = "This is a very , very long " "string that requires two lines."; ✌ ✆ Full example is given below: ✞ #include <iostream > 2 using namespace std; 4 int main (int argc , char *argv []) { char ch; 6 char string[] = "Two lines " "string."; 8 int i = 0; while (string[i] != ’0’) { 10 ch = string[i]; cout << ch; 12 i++; } 14 return 0; } ✌ ✆ ✞ T.w.o. .l.i.n.e.s. .s.t.r.i.n.g... ✌ ✆
  • 15. 2.1. ARRAY 195 When an array is declared and initialized with characters, there must be a terminating null character. Otherwise there shall be garbage output. For example following syntax has no terminating null character. It is not in standard format. ✞ 1 char a[10]; a[0]= ’a’; 3 a[1]= ’r’; a[2]= ’u’; ✌ ✆ In above method, a null terminator is added as its last element. Now, the string array is initialized in standard format. ✞ char a[10]; 2 a[0]= ’a’; a[1]= ’r’; 4 a[2]= ’u’; a[3]= ’0’; ✌ ✆ See following two examples, in which string is terminating without and with null termi- nating character. First example gives garbage output (see below). ✞ 1 #include <iostream > using namespace std; 3 int main (int argc , char *argv []) { 5 char a[10]; a[0] = ’a’; 7 a[1] = ’r’; a[2] = ’u’; 9 cout << a; return 0; 11 } ✌ ✆ ✞ <garbage output > ✌ ✆ In this second example, string is terminated with null character. This example gives output what we required. ✞ 1 #include <iostream > using namespace std; 3 int main (int argc , char *argv []) { 5 char a[10]; a[0] = ’a’; 7 a[1] = ’r’; a[2] = ’u’; 9 a[3] = ’0’; cout << a; 11 return 0; } ✌ ✆
  • 16. 196 Array & Pointer ✞ aru ✌ ✆ Static array size should be larger than one to the required size of the array to store data. For example, to store one byte data, array size should be two. Similarly, for storing n bytes data, array size should be at least n + 1. 2.1.6 Size of Array C++ features two kinds of arrays: static (compile-time, fixed size) and dynamic (allocated at run-time). The length of a dynamic array cannot be acquired from the array itself - its length must be stored elsewhere. The size of array is computed as ✞ 1 int length = sizeof(<array name >) / sizeof(<array element >); ✌ ✆ Preprocessor ways for array length is defined as ✞ 1 #define ARRAY_LENGTH (A) (sizeof(A) / sizeof(A[0]) ) ✌ ✆ Arrays become pointers when passed as a parameter to a function. Thus, the length of an array parameter may not require directly. A dedicated length parameter is required. An example is given below. ✞ 1 #include <iostream > using namespace std; 3 int main (int argc , char *argv []) { 5 const char *fruit[2] = {"apples", "oranges"}; 7 /* Length of the array by dividing * *the size of all elements by the* 9 *size of the first element. */ 11 int length = sizeof (fruit) / sizeof (fruit[0]) ; 13 cout << length; 15 return 0; } ✌ ✆ ✞ 2 ✌ ✆ In above example, length of the array is obtained by dividing the size of all elements (found with sizeof (fruit)) by the size of the first element. Note that since the array elements are pointers to null-terminated character arrays, the size of the first element is actually the size of the pointer type - not the length of the string. This size, regardless of the type being pointed to, is 8 bytes, 4 bytes, or 2 bytes on 64-bit, 32-bit, or 16-bit platforms respectively. Pointer can be used for variable size array as shown in example below.
  • 17. 2.2. POINTER 197 ✞ 1 #include <iostream > using namespace std; 3 /* Variable size array.*/ char *name ; 5 int main (int argc , char *argv []) { 7 name = "My School!!"; int i = 0; 9 while (name [i] != ’0’) { cout << name [i] << endl ; 11 i++; } 13 return 0; } ✌ ✆ ✞ M y S c h o o l ! ! ✌ ✆ 2.2 Pointer A pointer is a simple variable that stores address (the location in memory) of a value in memory rather than storing data itself. There are four fundamental things for the pointers: 1. How to declare them. 2. How to assign them. 3. How to reference the value to which the pointer points, i.e value finding also known as dereferencing. 4. How they relate to arrays. Two important rules of the pointer must be remembered. These are: 1. A variable name with prefixed by ampersand (&) defines the address of the variable and therefore points to the variable. 2. A pointer with prefixed by asterisk (*) refers to the value of the variable pointed-by the pointer.
  • 18. 198 Array & Pointer An array name is also an address of the first element of the array. Assume, ‘arr’ is an array as relation geven below: ✞ arr == &arr [0]; ✌ ✆ Here both ‘arr’ and ‘&arr[0]’ represent to the memory address of first element of the same array. A pointer can points to any element of an array, if the pointer is assigned address of that element. In the following example, pointer ‘x’ points to the address of first element of tha array ‘i’. ✞ 1 #include <iostream > using namespace std; 3 int main (int argc , char *argv []) { 5 int i[5] = {10, 20, 30, 40, 50}; int *x = &i[0]; /* Points to first element.*/ 7 cout << *x; return 0; 9 } ✌ ✆ 0 10 1 20 2 30 3 40 4 50 i[]: x The output of above program shall be ✞ 10 ✌ ✆ If above example is modified as given below, then the pointer ‘x’ points to the 3rd element of the array ‘i’. ✞ 1 #include <iostream > using namespace std; 3 int main (int argc , char *argv []) { 5 int i[5] = {10, 20, 30, 40, 50}; int *x = &i[2]; /* Points to third element.*/ 7 cout << *x; return 0; 9 } ✌ ✆ 0 10 1 20 2 30 3 40 4 50 i[]: x
  • 19. 2.2. POINTER 199 The output of above program shall be ✞ 30 ✌ ✆ If an intger is pointed by a pointer-to-char variable, then this variable can points to the address of each byte of the integer variable (integer variable is 4 bytes long). ✞ 1 #include <iostream > using namespace std; 3 int main (int argc , char *argv []) { 5 /* 1000 D = 1111101001 B*/ int i = 1001; 7 /* Pointer casting from integer to character .*/ char *x = (char *) &i; 9 /* Little endian is x[0]=11101001 B* *Big endian is x[1]=00000011 B* 11 *Big endian x[2]= x[3]=00000000 B*/ /* Print little endian x[0]*/ 13 cout << (int) x[0] << endl ; return 0; 15 } ✌ ✆ x[3] x[2] x[1] x[0] i: x 00000000 00000000 00000011 11101001 Output of above program is ✞ -23 ✌ ✆ ✞ 1 #include <iostream > using namespace std; 3 int main (int argc , char *argv []) { 5 /* 1000 D = 1111101001 B*/ int i = 1001; 7 /* Pointer casting from integer to character .*/ char *x = (char *) &i; 9 /* Little endian is x[0]=11101001 B* *Big endian is x[1]=00000011 B* 11 *Big endian x[2]= x[3]=00000000 B*/ /* Print big endian x[1]*/ 13 cout << (int) x[1] << endl ; return 0; 15 } ✌ ✆
  • 20. 200 Array & Pointer x[3] x[2] x[1] x[0] i: x 00000000 00000000 00000011 11101001 Output of above program is ✞ 3 ✌ ✆ 2.2.1 Declaring Pointers In C, pointers are declared as shown in following syntax. ✞ 1 long *var1 , var2 ; int **p3; ✌ ✆ In these syntax, line 1 declares ‘var1’ as a pointer to a long and ‘var2’ as a long and not a pointer to a long. In line 2, ‘p3’ is declared as a pointer to a pointer to an int. In C++, a pointer is declared as shown in the following syntax. ✞ int * A; 2 int * ptrA , ptrB ; ✌ ✆ Here ‘A’, ‘ptrA’ are pionter to integer while ‘ptrB’ is an ordinary integer. See an example given below: ✞ #include <iostream > 2 using namespace std; 4 int main (int argc , char ** argv ) { int i; 6 int* p, j; p = &i; /* valid for best practice */ 8 i = 10; /*i is now 10 */ *p = 20; /* valid*/ 10 j = 5; /* prints 20*/ 12 cout << "i is " << i << endl ; cout << "i is " << *p << endl ; 14 /* prints 5*/ cout << "j is " << j << endl ; 16 return 0; } ✌ ✆ ✞ i is 20 i is 20 j is 5 ✌ ✆
  • 21. 2.2. POINTER 201 1 0x49 2 0x50 3 0x51 4 0x52 5 0x53 6 0x54 7 0x55 int *p = &i i &i Pointer types are often used as parameters to function calls. ✞ 1 int MyFunction ( struct MyStruct *pStruct ); ✌ ✆ In the above syntax, it is explained that how to declare a function which uses a pointer as an argument. Since C++ passes function arguments by value, in order to allow a function to modify a value from the calling routine, a pointer to the value must be passed. Pointer- to-Structure is also used as function arguments even when nothing in the struct will be modified in the function. This is done to avoid copying the complete contents of the structure onto the stack. A simple example is ✞ 1 #include <iostream > /* time .h C library in C++ header as ctime*/ 3 #include <ctime > using namespace std; 5 void getSeconds (unsigned long *par); 7 int main (int argc , char ** argv []) { 9 unsigned long sec; getSeconds (& sec); 11 cout << "Number of seconds since 01 Jan 1970 : " << sec; return 0; 13 } 15 void getSeconds (unsigned long *par) { *par = time (NULL ); 17 return; } ✌ ✆ ✞ Number of seconds: 1420616845 ✌ ✆ 2.2.2 Pointer to Member A member of a structure or class or a namespace are also accessible via pointers. A pointer to member shall not point to a static member of a class, i.e. a member with reference type. “pointer to member” is distinct from the type “pointer”, therefore, a pointer to member is declared only by the pointer to member declarator syntax, and never by the pointer declarator syntax. ✞ 1 int X::* i = &X::a; // pointer to member method int *i = &a; // pointer declarator method ✌ ✆
  • 22. 202 Array & Pointer See the example below: ✞ #include <cstdlib > 2 #include <iostream > using namespace std; 4 struct X { 6 int a; }; 8 int main (int argc , char ** argv ) { 10 /* Declare member function i as pointer * *to the original member a of the struct*/ 12 int X::* i = &X::a; X x; 14 x.*i = 10; cout << x.*i; 16 return 0; } ✌ ✆ ✞ 10 ✌ ✆ 2.2.3 Pointer Address Pointers are used to point the memory address where data is stored. A pointer size is determined by the pointer data type. For example if pointer is character type then size of pointer is one byte. The pointer increment is one byte long. For example, ✞ 1 string *ptr= new string [8]; ✌ ✆ and pointer ‘ptr’ points to memory address 0×00 then ‘ptr++’ points to the memory address 0×01 as shown in the following figure. d 0x00 e 0x01 f 0x02 g 0x03 h 0x04 i 0x05 j 0x06 k 0x07 Bytes ptr ptr++ *ptr (*ptr)++ Again ‘*ptr’ points to the character ‘d’ at the memory address pointed by the pointer ‘ptr’. To get the next character ‘e’, dereference is done as ‘(*ptr)++’. Similarly, if pointer is integer type as declared below: ✞ 1 int *ptr= new int [10]; ✌ ✆
  • 23. 2.2. POINTER 203 then size of ‘ptr’ is 4 bytes. Now, if pointer ‘prt’ points to the memory address 0×00 then ‘ptr++’ points to the memory address 0×04 as shown in the figure given below: xxxx 0x00 xxxx 0x01 xxxx 0x02 xxxx 0x03 yyyy 0x04 yyyy 0x05 yyyy 0x06 yyyy 0x07 Bytes ptr ptr++ *ptr (*ptr)++ Again ‘*ptr’ points to the integer value at the memory address pointed by the pointer ‘ptr’. To get the next integer value, dereference is done as ‘(*ptr)++’. Remember that precedence of ‘++’ symbol is higher to asterisk (*) symbol. This is why to scope of asterisk (*) is changed by using parenthesis. 2.2.4 Assigning Values to Pointers To assign address of a variable to a pointer, unary operator ‘&’, also known as ‘address of’ operator is used as shown in the following syntax. ✞ 1 /*An interger variable that have * *null value stored in memory. */ 3 int myInt; /* Pointer that addresses to an integer value.*/ 5 int * ptr; /* Address to the pointer where * 7 *myInt value is stores in memory.*/ ptr = &myInt; ✌ ✆ Here, ‘ptr’ is referencing to ‘myInt’ now. Pointers can also be assign the address of dynamically allocated memory. See the following example. ✞ #include <iostream > 2 using namespace std; 4 int j, k; int * ptr; 6 int main (int argc , char ** argv ) { 8 j = 1; k = 2; 10 ptr = &k; cout << "j = " << j << ". It stored at " << (void *) &j << endl ; 12 cout << "k = " << k << ". It stored at " << (void *) &k << endl ; cout << "‘ptr’ = " << ptr << ". It stored at " 14 << (void *) &ptr << endl ; cout << "Value of the integer pointed -by ‘ptr’ is " << *ptr << endl ; 16 return 0;
  • 24. 204 Array & Pointer } ✌ ✆ ✞ j has value 1 and stored at 0x403100 k has value 2 and stored at 0x403120 ‘ptr ’ has value 0x403120 and stored at 0x403110 Value of the integer pointed -by ‘ptr ’ is 2 ✌ ✆ Assigning a value to a pointer requires specialization. In C++, it is best practice that first assign the address of a value to the pointer. We can retrieve the value from the address by dereferencing it using asterisk (‘*’); ✞ int * j; 2 int k = 5; j = &k/* Valid & good practice .*/ ✌ ✆ See the example ✞ 1 #include <iostream > using namespace std; 3 int main (int argc , char ** argv ) { 5 int * j; int k = 15; 7 j = &k; /* valid & good practice */ cout << "j is : " << *j; 9 return 0; } ✌ ✆ ✞ j is : 15 ✌ ✆ Assigning a value to a pointer directly causes errors in the C++ program. Therefore, it is not assumed a good practice. Sometimes, confusion creates a bad way for assignment of a value to a pointer as shown below: ✞ 1 int * j; *j = 5;/* Invalid & very bad practice .*/ ✌ ✆ It is as we try to assign a value to an uninitialized pointer. A pointer points to the location (address) where value is stored. Pointer does not store value itself. So, pointer does not know where value is stored. If we try to do so, the program either may crash or it damaged to the system. ✞ #include <iostream > 2 using namespace std; 4 int main (int argc , char ** argv ) { int i; 6 int *p; p = &i; /* valid for best practice */
  • 25. 2.2. POINTER 205 8 i = 10; /*i is now 10 */ *p = 20; /* valid*/ 10 /* prints 20*/ cout << "i is " << i << endl ; 12 cout << "i is " << *p << endl ; return 0; 14 } ✌ ✆ ✞ i is 20 i is 20 ✌ ✆ When we create a pointer in C++, the computer allocates memory to hold an address, but it does not allocate memory to hold the data to which the address points. Space for data is created by another step. If we omit the step required to create space for data attracts the errors. ✞ int * i; 2 *i = 10; ✌ ✆ Here, i is a pointer but it point to nothing. Therefore, code failed to assign an address to i. See the example below, which will failed to give desired output. ✞ #include <iostream > 2 using namespace std; 4 int main (int argc , char ** argv ) { int* p; 6 *p = 5; cout << "p is " << *p << endl ; 8 return 0; } ✌ ✆ In C++, memory for pointer is allocated by new operator. To allocate memory for integer we use the syntax like ✞ 1 int * j = new int; ✌ ✆ We tell to operator new for what data type we want in memory. It finds a block of the correct size and returns the address of the block. A practical example is given below: ✞ 1 #include <iostream > using namespace std; 3 int main (int argc , char ** argv ) { 5 int *j = new int; *j = 5; /* valid & good practice */ 7 cout << "j is : " << *j; return 0; 9 } ✌ ✆
  • 26. 206 Array & Pointer ✞ j is : 5 ✌ ✆ Each allocated memory by new operator only should be freed by delete operator. It is used as ✞ 1 int *j = new int;/* Create & reserve memory space*/ delete j; /* Free memory space*/ ✌ ✆ The use of delete operator as given below is illegal. ✞ int i = 5; 2 int *j = &i; delete j; /* illegal */ ✌ ✆ 2.2.5 Pointer Dereferencing (Value Finding) To access a value to which a pointer points, the asterisk (‘*’) operator is used. An- other operator, the ‘−>’ (Indirection) operator is used in conjunction with pointers to structures. Here’s a short example. ✞ 1 #include <iostream > using namespace std; 3 int main (int argc , char ** argv ) { 5 int i; int *p; // Pointer type int * 7 p = &i; // p now points to i i = 10; // i is now 10 9 *p = 20; // i is now 20!! /* prints "20" */ 11 cout << "i is " << i << endl ; /* "20"! dereferencing -p is the same as i!*/ 13 cout << "i is " << *p << endl ; return 0; 15 } ✌ ✆ ✞ i is 20 i is 20 ✌ ✆ 2.2.6 Addition of Pointers A pointer when dereferences, retrieves the value at the address pointed by the pointer. If the value at pointer address is an integer then we can add another integer value to it. When an integer value is addedd to the pointer then old addres of the pointer is changed into new address. Difference between new address and old address is equal to the pointer data type. In the following example, we retrieve the pointer value and add 1 to in function ‘increment()’.
  • 27. 2.2. POINTER 207 ✞ #include <iostream > 2 using namespace std; 4 void increment (int *p) { *p = *p + 1; /* Add one to p */ 6 } 8 int main (int argc , char ** argv ) { int i = 20; 10 /* i value is 20 */ cout << "i is " << i << endl ; 12 /* Pass interger to increment function as pointer */ increment (&i); 14 /* Print the value 21*/ cout << "i is " << i << endl ; 16 return 0; } ✌ ✆ ✞ i is 20 i is 21 ✌ ✆ The value of a pointer is the address of the object to which it points. The address of a large object, such as type double variable, typically is the address of the first byte of the object. Applying the * operator to a pointer yields the value stored in the pointed-to object. Adding 1 to the pointer increases its value by the size, in bytes, of the pointed-to type. 2.2.7 Pointers and Arrays If we have to use pointer for an array, then we use new operator to create a dynamic array of specific size. The valid types of dynamic allocation of array memory space are shown below: ✞ int * i = new int [10];/* 40 bytes space for 10 elements */ 2 string * str = new string [10];/*10 bytes string.*/ ✌ ✆ new operator returns the address of the first element of the block. We should free the allocated memory space by delete operator when program does not need it. Single block of memory should be created and freed like ✞ int * i = new int; /* Single byte memory space*/ 2 delete i; /* Free the allocated memory space*/ ✌ ✆ A dynamic array memory space should be created and freed like ✞ int * i = new int [10]; /*10 block memory */ 2 delete [] i; /* Free memory allocated for array*/ ✌ ✆
  • 28. 208 Array & Pointer Here ‘[]’ between delete operator and variable ‘i’ tells the program that it should free the whole array, not just the element pointed to by the pointer. ✞ #include <iostream > 2 using namespace std; 4 int main (int argc , char ** argv ) { int * mk = new int [10]; 6 *mk = 65874859; cout << *mk << endl ; 8 delete [] mk; return 0; 10 } ✌ ✆ ✞ 65874859 ✌ ✆ To add a value to a pointer we can use ‘*’ (asterisk) operator as well as array element method to the dynamically allocated array as shown in following example. ✞ 1 #include <iostream > using namespace std; 3 int main (int argc , char ** argv ) { 5 int * mk = new int [5]; int i; 7 for (i = 0; i < 5; i++) { mk[i] = i; 9 } for (i = 0; i < 5; i++) { 11 cout << mk[i] << endl ; } 13 delete [] mk; return 0; 15 } ✌ ✆ ✞ 0 1 2 3 4 ✌ ✆ If we want to add and retrieve values to dynamically allocated memory by using pointer then initial pointer location must be restored to get the actual stored values. See the example below: ✞ 1 #include <iostream > using namespace std; 3 int main (int argc , char ** argv ) { 5 int * mk = new int [5];
  • 29. 2.2. POINTER 209 int i; 7 for (i = 0; i < 5; i++) { *mk = i; // assign value at pointer location 9 mk ++; // increase pointer location by one } 11 mk = mk -5; // Restore the initial position of the pointer. for (i = 0; i < 5; i++) { 13 cout << *mk << endl ; mk ++; 15 } delete [] mk; 17 return 0; } ✌ ✆ ✞ 0 1 2 3 4 ✌ ✆ Pointer arithmetic can be used to increment the pointer position and retrieval of the value stored at that address. ✞ 1 #include <iostream > #include <string > 3 using namespace std; 5 int main (int argc , char ** argv ) { int * mk = new int [5]; 7 int i; for (i = 0; i < 5; i++) { 9 mk[i] = i; } 11 for (i = 0; i < 5; i++) { cout << *(mk + i) << "t" << (mk [0] + i) << endl ; 13 } delete [] mk; 15 return 0; } ✌ ✆ ✞ 0 0 1 1 2 2 3 3 4 4 ✌ ✆ Pointers to Arrays An array can be initialized by using any of the following methods:
  • 30. 210 Array & Pointer ✞ 1 int myArr [3] = {a, b, c}; int * arrPtr = myArr; /* name of an array = address */ 3 int * arrPtr = &myArr[0]; /*or use address operator */ ✌ ✆ First line in above syntax is initialization of an array. In second line, ‘arrPtr’ is a pointer to the array ‘myArr’. In third line, ‘arrPtr’ points to the address of first element of the array ‘myArr’. See the following example, in which both methods are used to assign the same array to two different pointers by two different methods. ✞ 1 #include <iostream > #include <string > 3 using namespace std; 5 int main (int argc , char ** argv ) { double Marks[3] = {120.0 , 200.0 , 150.0}; 7 /* Here are two ways to get the address of an array*/ double * p1 = Marks; /* name of an array = address */ 9 double * p2 = &Marks [0]; /*or use address operator */ // with array element 11 cout << "p1 = " << p1 << ", *p1 = " << *p1 << endl ; cout << "p2 = " << p2 << ", *p2 = " << *p2 << endl ; 13 p1 = p1 + 1; p2 = p2 + 1; 15 cout << "Add 1 to the p1 & p2 pointers : n"; cout << "p1 = " << p1 << ", *p1 = " << *p1 << endl ; 17 cout << "p2 = " << p2 << ", *p2 = " << *p2 << endl ; p1 = p1 + 1; 19 p2 = p2 + 1; cout << "Add 1 to the p1 & p2 pointers : n"; 21 cout << "p1 = " << p1 << ", *p1 = " << *p1 << endl ; cout << "p2 = " << p2 << ", *p2 = " << *p2 << endl ; 23 return 0; } ✌ ✆ ✞ p1 = 0x22 ff40, *p1 = 120 p2 = 0x22 ff40, *p2 = 120 Add 1 to the p1 & p2 pointers : p1 = 0x22 ff48, *p1 = 200 p2 = 0x22 ff48, *p2 = 200 Add 1 to the p1 & p2 pointers : p1 = 0x22 ff50, *p1 = 150 p2 = 0x22 ff50, *p2 = 150 ✌ ✆ Pointers as Function Argument Pointers can also be used as function arguments in C++. Function prototype with pointer argument is shown below: ✞ int myFunc(int* a); ✌ ✆
  • 31. 2.2. POINTER 211 When we call this function, we use ‘&’ (address of) symbol to pass the address of a variable not the value of the variable as function argument. The function is called like ✞ 1 int i=10; // variable i with assigned value 10 myFunc(&i); // pass address of i to function myFunc ✌ ✆ By this way, pointer ‘a’ is assigned the address of the function parameter ‘i’. In following example, a sum function takes two integer values as pointer and return their sum as integer. The call of sum function uses addresses of the two integer values by using address- of symbol (‘&’). ✞ #include <iostream > 2 using namespace std; 4 /*pass -by -value as pointers to a & b to sum()*/ int sum(int* a, int* b) { 6 int f; /* Passed values as a and b.* 8 *They can be changed here .*/ f = *a + *b; 10 return f; } 12 int main (int argc , char *argv []) { 14 int i = 2, j = 3, g; /* Pass address of i and j to sum * 16 *function not values of i and j */ g = sum (&i, &j); 18 cout << "Sum of " << 2 << ", " << 3 << " is " << g; return 0; 20 } ✌ ✆ ✞ Sum of 2, 3 is 5 ✌ ✆ 00000010 00000011 0xaa 0xbb i j g = sum(&i, &j);
  • 32. 212 Array & Pointer 00000010 00000011 0xaa 0xbb i j int sum(int* a, int* b) {} A pointer function can also be used as function argument, generally called function callback. See the example ✞ 1 #include <iostream > using namespace std; 3 int getSum(int i, int j, int (* PrintLabel )(int , int)) { 5 cout << "Sum of " << i << " and " << j << " is "; cout << PrintLabel (i, j); 7 } 9 int PrintLabel (int x, int y) { return (x + y); 11 } 13 int main (int argc , char *argv []) { 15 getSum (2, 4, PrintLabel ); return 0; 17 } ✌ ✆ ✞ Sum of 2 and 4 is 6 ✌ ✆ Address as Function Argument Address of can also be used as function argument in C++. Function prototype with address of argument is as: ✞ 1 int myFunc(int& a); ✌ ✆ Here, int& passes a reference to the function. When we call this function, we just pass the variables as argument. The function call should be like ✞ 1 int i=10; myFunc(i); ✌ ✆ In following example, a sum function takes addresses of two arguments and return their sum as integer. The function call of this sum function uses variables as function argu- ments.
  • 33. 2.2. POINTER 213 ✞ #include <iostream > 2 using namespace std; 4 /*pass -by -value as address of a & b to sum()*/ int sum(int& a, int& b) { 6 int f; /* Passed values as a and b.* 8 *They can be changed here .*/ f = a + b; 10 return f; } 12 int main (int argc , char *argv []) { 14 int i = 2, j = 3, g; /* Sum function with arguments i and j*/ 16 g = sum(i, j); cout << "Sum of " << 2 << ", " << 3 << " is " << g; 18 return 0; } ✌ ✆ ✞ Sum of 2, 3 is 5 ✌ ✆ 2.2.8 Constant Pointers A pointer may be declared as constant by using const keyword. ✞ 1 int i = 5; const int *p = &i; 3 //Or int const *p = &i; ✌ ✆ There are two cases, (i) where a pointer pointed to constant data (pointee) and pointee can not be changed, and (b) where constant pointer (address) can not be changed. The usual pointer-pointee relation are given below: ✞ #include <iostream > 2 using namespace std; 4 int main () { int i = 2; 6 int j = 3; int *k = &j; // k points to j and *k is 3 8 cout << *k << endl ; j = 6; // Now both j and *k are 6 10 cout << j << " " << *k << endl ; *k = 7; // j and *k are 7. Pointee changes 12 cout << j << " " << *k << endl ; k = &i; // k points to i. *k is 2. Pointer changes 14 cout << i << " " << *k << endl ;
  • 34. 214 Array & Pointer *k = 8; // i and *k are 8 now. Pointee changes 16 cout << i << " " << *k << endl ; return 0; 18 } ✌ ✆ ✞ 3 6 6 7 7 2 2 8 8 ✌ ✆ Now the const keyword is used as shown in modified example. There are errors shows by the compiler. ✞ 1 #include <iostream > using namespace std; 3 int main () { 5 int i = 2; const int j = 3; 7 const int *k = &j; j = 6; // Error! assignment of read -only variable ’j’ 9 *k = 7; // Error! assignment of read -only location ’* k’ k = &i; // k points to i. *k is 2. Pointer changes 11 *k = 8; // Error! assignment of read -only location ’* k’ return 0; 13 } ✌ ✆ Here, code line ✞ 1 //+--Pointee type , i.e. constant pointee //| 3 const int *k = &j; ✌ ✆ 1 0x49 2 0x50 3 0x51 4 0x52 5 0x53 6 0x54 7 0x55 const int *k = &j j &j (const) j represents that ‘k’ is a non constant type pointer and the value to which it is pointing is constant type. Therefore, value of ‘j’ can not be changed while address of ‘k’ can be changed. ✞ 1 #include <iostream > using namespace std;
  • 35. 2.2. POINTER 215 3 int main () { 5 int i = 2; const int j = 3; 7 const int *k = &j; // int const *k = &j; // Or state 9 cout << "Address of k is " << k << endl ; k = &i; // k points to i. *k is 2. Pointer changes 11 cout << "New address of k is " << k << endl ; // 13 cout << "i : " << i << ", k : " << *k << endl ; return 0; 15 } ✌ ✆ ✞ Address of k is 0x22ff44 New address of k is 0x22 ff48 i : 2, k : 2 ✌ ✆ Similarly, if ✞ 1 // +--Pointer type , i.e. constant pointer // | 3 int * const k = &j; ✌ ✆ then, pointer becomes constant while value of pointee can be changed. Notice the position of asterisk (*) not the const keyword. 1 0x49 2 0x50 3 0x51 4 0x52 5 0x53 6 0x54 7 0x55 int * const k = &j (const) *k j &j ✞ 1 #include <iostream > using namespace std; 3 int main () { 5 int i = 2; int j = 3; 7 int * const k = &j; cout << "Address of k is " << k << endl ; 9 cout << "Old values - j : " << j << ", k : " << *k << endl ; j = 5; // k points to i. *k is 2. Pointer changes 11 cout << "New values - j : " << j << ", k : " << *k << endl ; //k = &i;// Error! assignment of read -only variable ’k’ 13 return 0; } ✌ ✆
  • 36. 216 Array & Pointer ✞ Address of k is 0x22ff44 Old values - j : 3, k : 3 New values - j : 5, k : 5 ✌ ✆ The change in the position of the asterisk (*) and keyword const changes the pointer and pointee type. The general representation is ✞ 1 int n = 5; int * p = &n; // non -const -Pointer to non -const -Pointee 3 const int * p = &n; // non -const -Pointer to const - Pointee int * const p = &n; // const -Pointer to non -const - Pointee 5 const int * const p = &n; // const -Pointer to const -Pointee ✌ ✆ 2.2.9 Pointers to Function A pointer to function is defined as ✞ 1 void (*fp)(); ✌ ✆ This function has no return value and no arguments (i.e. parameters). Here parentheses ( ) is used to encapsulate asterisk and function name. The reason is that parentheses operator, ( ), has higher precedence than that of dereferencing operator (*). Hence for pointer-to-function variable, dereferencing of function is grouped by parentheses. Exam- ple for pointer-to-function is given below. ✞ 1 #include <iostream > 3 using namespace std; 5 void myFunc () { cout << "Function is called ..." << endl ; 7 } 9 int main (int argc , char *argv []) { void (*r)(); 11 r = myFunc; (*r)(); 13 return 0; } ✌ ✆ ✞ Function is called ... ✌ ✆ A pointer to a function is possible in C++. This type of function may accepts arguments as pointers. The return value from the function is pointed by the function itself. In following example, a pointer-to-function is used. ✞ 1 #include <iostream > using namespace std;
  • 37. 2.2. POINTER 217 3 int* f(int* x) { 5 (*x)++; return x; 7 } 9 int main (int argc , char *argv []) { int a = 1; 11 cout << f(&a) << endl ; cout << *f(&a) << endl ; 13 return 0; } ✌ ✆ ✞ 0x22ff5c 3 ✌ ✆ Sometimes pointer-to-function returns the pointer to local variable. It is not considered a good practice. Compiler shows warning when we do so. It should be avoid in program- ming. 2.2.10 Pointer Arithmetic In normal mathematics numbers are used for addition, subtraction, division and multipli- cation etc. A pointer to an integer has different behavior to the integer. This is why, in pointer arithmetic, we have to arrange or conform the pointers so that they can behave in properly. A pointer-to-variable always points to the address where value of the variable is stored. This is why direct arithmetic of the pointers is of the arithmetic of the address rather than the values stored at the addresses. For example, we have to create an array of 2 element size (cells). Store a value in first cell. Retrieve the value and increment it by one. In the following example, we implement the solution as given below: ✞ #include <iostream > 2 using namespace std; 4 int main (int argc , char *argv []) { int i [10]; 6 int* a = i; cout << "a is " << (long ) a << endl ; 8 a++; cout << "a++ is " << (long ) a << endl ; 10 return 0; } ✌ ✆ ✞ a is 2293556 a++ is 2293560 ✌ ✆ In above example, the increment operator adds 4 to the address of pointer-to-integer variable ‘a’ rather that its value. This is why, we need proper confer to the pointer to
  • 38. 218 Array & Pointer the desired result. In the following example, we uses proper way of pointe and get the desired result. ✞ #include <iostream > 2 using namespace std; 4 int main (int argc , char *argv []) { int i [2]={1}; /*1st=1, 2nd=0*/ 6 int* a = i; cout << "a is " << *a << endl ; 8 *a++; /* Increment to pointer index* *and get value which is 0 */ 10 cout << "a++ is " << *a << endl ; return 0; 12 } ✌ ✆ ✞ a is 1 a++ is 0 ✌ ✆ The result is not as we sought in result. Above code is again modified as given below: ✞ #include <iostream > 2 using namespace std; 4 int main (int argc , char *argv []) { int i [2]={1}; /*1st=1, 2nd=0*/ 6 int* a = i; cout << "a is " << *a << endl ; 8 (*a)++; /* Increment to value of a*/ cout << "a++ is " << *a << endl ; 10 return 0; } ✌ ✆ ✞ a is 1 a++ is 2 ✌ ✆ This is the result what we sought in our problem. Similarly, in following example, we use pointers in simple arithmetic. ✞ #include <iostream > 2 using namespace std; 4 int main (int argc , char *argv []) { int a = 9, b = 5; 6 int* i = &a; int* j = &b; 8 cout << "Sum of i, j is " << (*i + *j) << endl ; cout << "Subtraction of i, j is " << (*i - *j) << endl ; 10 cout << "Division of i, j is " << (*i / *j) << endl ; cout << "Multiplication of i, j is " << (*i * *j) << endl ;
  • 39. 2.2. POINTER 219 12 return 0; } ✌ ✆ ✞ Sum of i, j is 14 Subtraction of i, j is 4 Division of i, j is 1 Multiplication of i, j is 45 ✌ ✆
  • 41. 3.1. STREAM & BUFFER 221 3Accessing System Files Standard Input-Output and access of files is a main part of computer programming. In this chapter we shall discuss the importance and methodology of accessing system and user define files. 3.1 Stream & Buffer 3.1.1 File Stream fstream is a header which includes the objects for reading a file or writing a file. It is just a file stream. Operations on the open file are performed by the objects/member functions of the fstream class. 3.1.2 File Buffer filebuf is a stream buffer that is used to read from a file or write to a file. It is constructed without association, these objects are associated to a file by calling its member open. Once open, all input/output operations performed on the object are reflected in the associated file. rdbuf () reads the file at once completely and put it in read buffer stream. See the example below: ✞ #include <fstream > 2 #include <iostream > using namespace std; 4 int main (int argc , char * argv []) { 6 ifstream inF("a.txt"); cout << inF.rdbuf(); 8 return 0; } ✌ ✆ streambuf is a stream buffer and is an object in charge of performing the reading and writing operations of the stream object it is associated with. The stream delegates all such operations to its associated stream buffer object, which is an intermediary between the stream and its controlled input and output sequences. 3.2 Accessing Files Files are named memory locations where data is stored in text or binary form. Each file that exists in the disk can be accessed, read and write if it is not specially granted restricted permissions. Users may create, access, update and delete a file by using C++ program.
  • 42. 222 Accessing System Files 3.2.1 Open A File A file in C++ can be opened in read, write, truncate or append mode. The flags used to open a file are given in following table. Flags Meaning ios::in Opens an input file without truncating the existing file. (ifstream) ios::ate Opens an existing file and seeks the end. ios::out Opens an output file. By default, ios::trunc is implied. (ofstream) ios::app Opens an output file for appending data. ios::nocreate Opens a file only if it already exists. ios::noreplace Opens a file only if it does not exist. ios::trunc Opens a file in truncate mode. ios::binary Opens a file in binary mode. Default is text mode. Table 3.1: File opening mode. To open a file, one can either call open on the file stream or, more commonly, use the constructor. One can also supply an open mode to further control the file stream. For reading-writing of the file, ‘fstream’ header file is used. ✞ 1 #include <fstream > using namespace std; 3 int main (int argc , char *argv []) { 5 ofstream file1; 7 file1.open ("file1.txt", ios:: app); file1 << "Appended data .n"; 9 ofstream file2("file2.txt"); 11 file2 << "Replace data .n"; 13 return 0; } ✌ ✆ Each file opened must be closed by using function close(). On unsuccessful, a flag is set in the stream object. The flag status is checked by good(), bad() or fail() member functions, which return a boolean value. The stream object doesn’t throw any exceptions in such a situation, hence manual status check is required. ✞ #include <iostream > 2 #include <fstream > using namespace std; 4
  • 43. 3.2. ACCESSING FILES 223 int main (int argc , char *argv []) { 6 /* Try to open non -exist file xyz.txt.* 8 *fstream does not show any errors. */ ifstream file1; 10 file1.open ("zyz.txt", ios::in); 12 /*To check whether a xyz.txt is really* *opened or not , we use good () object.*/ 14 cout << file1.good (); /* Returns 0*/ cout << endl ; 16 /* Try to open existing file a.txt. */ 18 ifstream file2; file2.open ("a.txt", ios::in); 20 /*To check whether a a.txt is really * 22 *opened or not , we use good () object.*/ cout << file2.good (); /* Returns 1*/ 24 } ✌ ✆ ✞ 0 1 ✌ ✆ fail() tries to read the next character from the input stream. If it fails to read the next character due to EOF, it returns true otherwise it returns false. ✞ #include <iostream > 2 using namespace std; 4 int main (int argc , char ** argv ) { char name ; 6 cout << "Enter the name : "; cin.get(name ); 8 while (cin.fail () == false) { cout << name << endl ; 10 cin.get(name ); } 12 return 0; } ✌ ✆ 3.2.2 Read File Data While reading a file, input from the in-stream is assigned to a string variable, until the file or in-stream does not reach to EOF pitfall or until an error does not occur. getline() function is used for this purpose. ✞ 1 #include <fstream > #include <string >
  • 44. 224 Accessing System Files 3 #include <iostream > using namespace std; 5 int main (int argc , char ** argv ) { 7 /* Line number counter */ int linecount = 0; 9 string line ; /* Open input file */ 11 ifstream inFile("file1.txt"); /*If input file is successfully opened.*/ 13 if (inFile) { /* Read line by line of text file . * 15 *until end of file is not found. */ while (getline(inFile , line )) { 17 /* Print the line number and line */ cout << linecount << ": " << line << ’n’; 19 /* Increment the line number */ linecount ++; 21 } } 23 /* Close input file .*/ inFile.close(); 25 return 0; } ✌ ✆ We can also read a file byte by byte as the method given below: ✞ #include <fstream > 2 #include <string > #include <iostream > 4 using namespace std; 6 int main (int argc , char ** argv ) { ifstream is("file1.txt"); 8 char c; 10 while (is.get(c)) cout << c << endl ; 12 is.close(); 14 return 0; 16 } ✌ ✆ To check whether the file has been reached to its end, eof () member function is used as shown in the syntax given below. ✞ if (infile.eof()) break ✌ ✆
  • 45. 3.2. ACCESSING FILES 225 Infile Stream ifstream operator is used to open an input file stream. It is always followed by input stream name. A file name is argument of the input stream name. To use this operator, header file ‘fstream’ is required. Syntax of ifstream is given as ✞ 1 ifstream <stream name >("<file name >"); ✌ ✆ An example is given below: ✞ 1 #include <string > #include <fstream > 3 using namespace std; 5 int main (int argc , char *argv []) { /* Open a file stream to read */ 7 ifstream f1("a.txt"); ofstream f2("b.txt"); 9 string s; while (getline(f1 , s)) 11 f2 << s << "n"; } ✌ ✆ On execution, we shall get desired result. 3.2.3 Write File Data The data of user is stored in memory as data file. To write a file in memory, data is first transfer to out stream buffer and them it is flushed into the memory. Outfile Stream ofstream operator is used to open an output file stream. This is member of fstream (file stream) class. It is always followed by output stream name. A file name is argument of the output stream name. To use this operator, header file ‘fstream’ is required. Syntax of ofstream is given as ✞ ofstream <stream name >("<file name >"); ✌ ✆ An example is given below: ✞ 1 #include <string > #include <fstream > 3 using namespace std; 5 int main (int argc , char *argv []) { ifstream f1("a.txt"); 7 /* Open a file stream to write*/ ofstream f2("b.txt"); 9 string s; while (getline(f1 , s))
  • 46. 226 Accessing System Files 11 f2 << s << "n"; f1.close(); 13 f2.close()’ return 0; 15 } ✌ ✆ On execution, we shall get desired result. Concatenation of the strings is allowed in C++ by using operator ‘+=’. See the example below: ✞ 1 #include <string > #include <fstream > 3 #include <iostream > using namespace std; 5 int main (int argc , char *argv []) { 7 ifstream f1("a.txt"); /* Open a file stream to write*/ 9 ofstream f2("b.txt"); string s, line ; 11 while (getline(f1 , s)) line += s + "n"; 13 f2 << line ; cout << line ; 15 } ✌ ✆ 3.2.4 File As Function Argument A input or output file stream allows to pass a file pointer to a function as its argument. The syntax of argument is like ✞ 1 ifstream & <arg name > // for input file stream ofstream & <arg name > // for output file stream ✌ ✆ In the following example, out file stream is passed to function argument and contents are written in the out file. ✞ #include <iostream > 2 #include <fstream > using namespace std; 4 void PassToFunc (ofstream &f, int n) { 6 f << n; } 8 int main () { 10 ofstream f1("b.txt"); PassToFunc (f1 , 10); 12 return 0; } ✌ ✆ It creates a file “b.txt” in which integer 10 is written.
  • 47. 3.2. ACCESSING FILES 227 3.2.5 File Position We can access the location of file pointer by using tellp() for an out stream (ostream) and tellg() for an in stream (istream). seekp return the stream position (streampos) of an out stream (ostream) and seekg() returns the stream position of an in stream (istream). seekp and seekg() takes two arguments. First is number of byte, either positive or negative value and second is direction. The seek directions are Flags Meaning ios::beg From the beginning of stream. ios::cur From the current position of stream. ios::end From the end of stream. Table 3.2: Seek Directions. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 (1) fp (2) fp.seekp(-8, ios::cur) (3) fp (4) Figure 3.1: Change in location of file pointer from current file pointer location. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 (1) fp (2) fp.seekp(-8, ios::end) (3) fp (4) Figure 3.2: Change in location of file pointer from the end of file location.
  • 48. 228 Accessing System Files 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 (1) fp (2) fp.seekp(10, ios::beg) (3) fp (4) Figure 3.3: Change in location of file pointer from the beginning of file location. In following example, a file ‘a.txt’ is read and file pointer is set after 10bytes using seekg() function from the beginning of the file. The current position of the in file stream is return by using function tellg() function. ✞ 1 #include <fstream > #include <iostream > 3 using namespace std; 5 int main (int argc , char * argv []) { /* Open in file */ 7 ifstream inf("a.txt"); /* Set file pointer after 10 bytes* 9 *from beginning of current file */ inf.seekg(10, ios:: cur); 11 /* Get current position of file pointer */ cout << inf.tellg(); 13 return 0; } ✌ ✆ ✞ 10 ✌ ✆ In following example, we set the file pointer after 10 bytes from the end of the file location. ✞ 1 #include <fstream > #include <iostream > 3 using namespace std; 5 int main (int argc , char * argv []) { /* Open in file */ 7 ifstream inf("a.txt"); /* Set file pointer after -10 bytes* 9 *from the end of the current file */ inf.seekg(-10, ios:: end); 11 /* Get current position of file pointer */ cout << inf.tellg();
  • 49. 3.3. DATA STRUCTURES 229 13 return 0; } ✌ ✆ ✞ 228 ✌ ✆ For output stream, seekp() and tellp() functions are used. ✞ 1 #include <fstream > #include <iostream > 3 using namespace std; 5 int main (int argc , char * argv []) { /* Open out file */ 7 ofstream outf ("b.txt"); /* Set file pointer after 11 bytes* 9 *from beginning of current file */ outf . seekp(11, ios:: beg); 11 /* Get current position of file pointer */ cout << outf .tellp(); 13 return 0; } ✌ ✆ ✞ 11 ✌ ✆ We can write something after the specific position in the current out file by using ‘<<’ operator. ✞ 1 #include <fstream > #include <iostream > 3 using namespace std; 5 int main (int argc , char * argv []) { ofstream outf ("b.txt"); 7 outf . seekp(11, ios:: beg); outf << "This is my file "; 9 return 0; } ✌ ✆ 3.3 Data Structures A data structure (struct) contains multiple pieces of data. Each piece of data (called a “member”) can be accessed by using a group of instance of structure, followed by a ‘.’ (ie dot), then the name of the member (another way to access a member is using the member operator ‘−>’ for pointers.). The member variables of data structure can be of any data-type or can be an array or a pointer.
  • 50. 230 Accessing System Files 3.3.1 Struct A data structure contains multiple pieces of data. One defines a data structure using the struct keyword. For example, ✞ struct <mystruct >{ 2 int <int_member >; double <double_member >; 4 char <string_member [25] >; } <variable >; ✌ ✆ ‘variable’ is an instance of ‘mystruct’. One can omit it from the end of the struct decla- ration and declare it later using: ✞ 1 struct <mystruct > <variable >; ✌ ✆ It is often common practice to make a type synonym so we don’t have to type struct ‘mystruct’ all the time. The struct itself has no name (by the absence of a name on the first line), but it is aliased as ‘mystruct’. Then you can use ✞ 1 <mystruct > <variable >; ✌ ✆ We can add or read data in structure by just using ‘dot’ symbol as ✞ 1 struct student { int id; 3 char *name ; float perc ; 5 } st; st.id =1;/* use of dot symbol between instance name and struct element.*/ ✌ ✆ After creating an instance of structre, instance reserves the memory bytes equal to the sum of size of all members. See the figure given below: a b c d e f g h i j st id name perc Here is working example of struct function: ✞ #include <iostream > 2 using namespace std; 4 struct student { int id; 6 char *name ; float perc ; 8 } st , st1 , st2;
  • 51. 3.3. DATA STRUCTURES 231 10 int main (int argc , char *argv []) { st.id = 1; 12 st1.name = "Arun Umrao"; st2.perc = 90.5; 14 cout << "Id is: " << st.id << endl ; cout << "Name is: " << st1.name << endl ; 16 cout << "perc is: " << st2.perc << endl ; return 0; 18 } ✌ ✆ ✞ Id is: 1 Name is: Arun Umrao perc is: 90.5 ✌ ✆ Another simple example is given below. ✞ 1 #include <iostream > using namespace std; 3 struct data { 5 int val; float b; 7 }; 9 int main (int argc , char *argv []) { struct data s; 11 s.val = 12; s.b = 3.14159; 13 cout << "The val field in s is:" << s.val << endl ; return 0; 15 } ✌ ✆ ✞ The val field in s is: 12 ✌ ✆ Pointer can be also used in structure. An instance of a structure ‘data’ using a pointer is declared as ✞ 1 data *<variable >; ✌ ✆ Member values of the structure declared with pointer are initialized or accessed by using operator − >. See the following syntax, in which a structure ‘Func’ is declared by using a pointer and its member values are set by using operator − >. ✞ 1 struct Func { int val; 3 float fl; }; 5 struct Func *b; b->val = 3491; ✌ ✆
  • 52. 232 Accessing System Files st st++ val fl A working example is ✞ #include <iostream > 2 using namespace std; 4 struct Func { int val; 6 float fl; }; 8 int main (int argc , char *argv []) { 10 /* Func struct required for pointer */ struct Func a; 12 /* this is a pointer to a struct Func */ struct Func *b; 14 b->val = 3491; cout << "The value of b is " << b->val << endl ; 16 return 0; } ✌ ✆ ✞ The value of b is 3491. ✌ ✆ A struct data can also be passed to a function by using address of procedure. See the example below in which data struct is passed to function ‘Plantation’. ✞ 1 #include <iostream > using namespace std; 3 /* Data structure */ 5 struct Data { int Trees; 7 int Plants; }; 9 /* function Plantation with data structure as pointer */ 11 void Plantation (struct Data *f) { f->Trees = 10; 13 f->Plants = 20; } 15 int main (int argc , char *argv []) { 17 /* Struct data structure */ struct Data Bio; 19 /* Pass address ‘Bio ’ into struct ‘Data ’ as pointer */ Plantation (& Bio);
  • 53. 3.3. DATA STRUCTURES 233 21 cout << "Trees : " << Bio.Trees << endl ; /* prints "10" */ cout << "Plants : " << Bio.Plants << endl ; /* prints "20" */ 23 return 0; } ✌ ✆ ✞ Trees : 10 Plants : 20 ✌ ✆ A constant pointer, once holds an address cannot change to the new address. It means a constant pointer, if already pointing to an address, cannot point to a new address. ✞ #include <iostream > 2 using namespace std; 4 int main (int argc , char *argv []) { char ch = ’A’; 6 char cH = ’B’; 8 char * const ptr = &ch; // A constant pointer ptr = &cH; // Illegal way of pointer . 10 return 0; 12 } ✌ ✆ In case of pointer to structure, if the things on the left of the ‘.’ (dot) or ‘− >’ operator is qualified (with ‘const’ or ‘volatile’) then the result is also has those qualifiers associated with it. In the following example, when the pointer points to a qualified type the result got is also qualified. ✞ #include <iostream > 2 using namespace std; 4 struct myStruct { int i; 6 }; 8 int main (int argc , char *argv []) { /* Initialisation of structures . */ 10 struct myStruct *Ptr , s_item; /* Initialisation of structures of constant qualifier . */ 12 const struct myStruct *s_Ptr; /* Set the item value.*/ 14 s_item.i = 1; /* OK */ /* Assigning new pointer .*/ 16 Ptr = &s_item; Ptr ->i += 2; /* OK */ 18 /* Constant qualified pointer.*/ s_Ptr = &s_item; 20 s_Ptr ->i = 0; /* Not OK to point constant type qualifier . */ return 0;
  • 54. 234 Accessing System Files 22 } ✌ ✆ A structure can also be initialized at the starting of program if structure is defined as ✞ struct employee { 2 int no; int sex; 4 int age; }; 6 struct employee EmpNo={<int >, <int >, <int >}; ✌ ✆ The following example clears the initialization of the structure. ✞ #include <iostream > 2 using namespace std; 4 struct employee { int no; 6 int sex; int age; 8 }; 10 int main (int argc , char *argv []) { struct employee EmpNo = {10, 1, 15}; /* Initializing structure */ 12 cout << EmpNo.no << endl << EmpNo.sex << endl << EmpNo.age; return 0; 14 } ✌ ✆ Nested Structure When a loop is declared inside another loop then the inner loop is called nested loop. ✞ for (;;) { 2 for (;;) /* Nested for loop */ } ✌ ✆ Similarly, when a structure is declared inside another structure then it is called nested structure. Nested structure can be declared by using either normal variable or pointer. In following example, a nested structure is declared and declared by simple variable. ✞ 1 #include <iostream > using namespace std; 3 int main (int argc , char *argv []) { 5 /* date structure */ 7 struct date { int day; 9 int month; int year ;
  • 55. 3.3. DATA STRUCTURES 235 11 }; 13 /* variety structure */ struct variety {/* Upper level structure */ 15 char *name ; /* Nested structure . Declared by normal variable . * 17 * Element of the structure are accessed by dot (.)*/ struct date date ; /* Lower level structure as normal variable .*/ 19 } tr; /* Structure declared as normal variable . * * Elements can be accessed by (.) symbol.*/ 21 /* Accessing structure elements by using synopsis like 23 * up_level_struct (.) up_level_elem * or 25 * up_level_struct (.) low_level_struct (.) low_level_elem */ tr.name = "A"; 27 tr.date .day = 10; cout << "Name : " << tr.name << endl ; 29 cout << "day : " << tr.date .day << endl ; return 0; 31 } ✌ ✆ ✞ Name : A day : 10 ✌ ✆ In simple variable type declaration of structure, elements are accesses by using dot (.). Using of pointer symbol (−>) throws the errors. In above example, ‘name’ and ‘date’ are elements of the ‘variety’ structure. ✞ #include <iostream > 2 using namespace std; 4 int main (int argc , char *argv []) { 6 /* date structure */ struct date { 8 int day; int month; 10 int year ; }; 12 /* variety structure */ 14 struct variety {/* Upper level structure */ char *name ; 16 /* Nested structure . Declared by normal variable . * * Element of the structure are accessed by dot (.)*/ 18 struct date date ; /* Lower level structure as normal variable .*/ } tr; /* Structure declared as normal variable . * 20 * Elements can be accessed by (.) symbol.*/
  • 56. 236 Accessing System Files 22 /* Accessing structure elements by using synopsis like * up_level_struct (.) up_level_elem 24 * or * up_level_struct (.) low_level_struct (.) low_level_elem */ 26 tr.name = "A"; tr.date .day = 10; 28 /* Following line throws errors. Reason is that we are trying* *to access the element by pointer symbol (->) even though * 30 *the structure ‘tr ’ is declared here as normal variable . */ tr ->date .month = 11; 32 cout << "Name : " << tr.name << endl ; cout << "day : " << tr.date .day << endl ; 34 return 0; } ✌ ✆ By other way, we can use pointer method to assign one structure inside other structure. In pointer method, elements are accessed by using pointer symbol (−>) and dot (.). ✞ 1 #include <iostream > using namespace std; 3 int main (int argc , char *argv []) { 5 /* date structure */ 7 struct date { int day; 9 int month; int year ; 11 }; 13 /* variety structure */ struct variety {/* Upper level structure */ 15 char *name ; /* Nested structure . Declared by normal variable . * 17 * Element of the structure can accessed by dot (.)*/ struct date date ; /* Lower level structure as normal variable .*/ 19 } *tr; /* Structure declared as pointer variable . * * Elements can be accessed by (->) symbol.*/ 21 /* Accessing structure elements by using synopsis like * up_level_struct (->) up_level_elem 23 * or * up_level_struct (->) low_level_struct (.) low_level_elem */ 25 tr ->name = "A"; tr ->date .day = 10; 27 cout << "Name : " << tr ->name << endl ; cout << "day : " << tr ->date .day << endl ; 29 return 0; } ✌ ✆
  • 57. 3.3. DATA STRUCTURES 237 ✞ Name : A day : 10 ✌ ✆ Again, indirect membership operator or structure pointer operator (−>) is not used in the level or element of the structure declared as normal variable. ✞ #include <iostream > 2 using namespace std; 4 int main (int argc , char *argv []) { 6 /* date structure */ struct date { 8 int day; int month; 10 int year ; }; 12 /* variety structure */ 14 struct variety {/* upper level structure */ char *name ; 16 /* Nested structure . Declared by normal variable . * * Element of the structure are accessed by dot (.)*/ 18 struct date date ; /* Lower level structure as normal variable .*/ } *tr; /* Structure declared as pointer variable .* 20 * Elements are accessed by (->) symbol. */ /* Following lines throw errors. We are trying here to access * 22 *the elements of structure ‘date ’ by pointer symbol (->) while* *the structure ‘date ’ is declared here as normal variable . */ 24 tr ->date ->day = 10; tr.date ->day = 10; 26 return 0; } ✌ ✆ But the lower level elements can also be accessed by using pointer symbol (−>) if lower level structure is also declared as pointer level. ✞ 1 #include <iostream > using namespace std; 3 int main (int argc , char *argv []) { 5 /* date structure */ 7 struct date { int day; 9 int month; int year ; 11 };
  • 58. 238 Accessing System Files 13 /* variety structure */ struct variety {/* upper level structure */ 15 char *name ; /* Nested structure . Declared as pointer variable .* 17 * Element of the structure can accessed by (->) */ struct date *date ; /* Lower level structure as normal variable .*/ 19 } *tr; /* Structure declared as pointer variable . * * Elements can be accessed by (->) symbol.*/ 21 cout << "Date & Month :" << endl ; /* Accessing structure elements by using synopsis like 23 * up_level_struct (->) up_level_elem * or 25 * up_level_struct (->) low_level_struct (->) low_level_elem */ tr ->date ->day = 10; 27 tr ->date ->month = 10; cout << "Day : " << (tr ->date ->day) << endl ; 29 cout << "Month : " << (tr ->date -> month) << endl ; return 0; 31 } ✌ ✆ ✞ Date & Month : Day : 10 Month : 10 ✌ ✆ In above examples, it is clarified that, elements of structures declared as variable type are accessed by using dot (.) and elements of structure declared as pointer type are accessed by using indirect membership operator or structure pointer operator (-¿). ✞ 1 #include <iostream > using namespace std; 3 int main (int argc , char *argv []) { 5 /* date structure */ 7 struct date { int day; 9 int month; int year ; 11 }; 13 /* variety structure */ struct variety {/* up_level_struct (uls)*/ 15 char *name ; /* Nested structure . Declared as pointer variable .* 17 * Element of the structure are accessed by (->). */ struct date *date ; /* Lower level structure as normal variable .*/ 19 } tr; /* Structure declared as normal variable .* * Elements can be accessed by dot (.). */ 21
  • 59. 3.3. DATA STRUCTURES 239 /* Accessing structure elements by using synopsis like 23 * up_level_struct (.) up_level_elem * or 25 * up_level_struct (.) low_level_struct (->) low_level_elem */ tr.date ->day = 10; 27 tr.date ->month = 10; cout << "Day : " << (tr.date ->day) << endl ; 29 cout << "Month : " << (tr.date -> month) << endl ; return 0; 31 } ✌ ✆ ✞ Day : 10 Month : 10 ✌ ✆ Linked List See the followomg prototype for the definition of a structure: ✞ struct list_Elem { 2 int data ; struct list_Elem *ele_Ptr ; /* Element is structure itself.*/ 4 }; ✌ ✆ In this prototype, element of structure is structure itself. It is forbidden in the structure definition. But in fact it only contains a pointer to itself. It is allowed as by the time the compiler reaches the pointer declaration it already knows that there is such a thing as a ‘struct list Elem’ so the declaration is permitted. In fact, it is possible to make a incomplete declaration of a structure by saying ✞ struct list_Elem ; ✌ ✆ at some point before the full declaration. This will allow the declaration of pointers before the full declaration is seen. It is also important in the case of cross-referencing structures where each must contain a pointer to the other, as shown in the following example. ✞ 1 struct s_1; /* Incomplete type */ 3 struct s_2 { int something ; 5 struct s_1 *sp; }; 7 struct s_1 { /* Full declaration */ 9 float something ; struct s_2 *sp; 11 }; ✌ ✆ This illustrates the need for incomplete types. It also illustrates an important thing about the names of structure members: they inhabit a name-space per structure, so element
  • 60. 240 Accessing System Files names can be the same in different structures without causing any problems. Incomplete types may only be used where the size of the structure isn’t needed yet. A full declaration must have been given by the time that the size is used. The later full declaration mustn’t be in an inner block because then it becomes a new declaration of a different structure. ✞ 1 struct x; /* Incomplete type */ 3 /* valid uses of the tag */ struct x *p, func (void ); 5 void f1(void ) { 7 struct x { int i; 9 }; /* redeclaration ! */ } 11 /* full declaration now */ 13 struct x { float f; 15 } s_x; 17 void f2(void ) { /* valid statements */ 19 p = &s_x; *p = func (); 21 s_x = func (); } 23 struct x func (void ) { 25 struct x tmp; tmp.f = 0; 27 return (tmp); } ✌ ✆ The other principal way to get incomplete types is to declare arrays without specifying their size and their type is incomplete until a later declaration provides the missing information: ✞ int ar []; /* incomplete type */ 2 int ar [5]; /* completes the type */ ✌ ✆ If you try that out, it will only work if the declarations are outside any blocks (external declarations), but that’s for other reasons. There were three elements linked into the list, which could have been built like this: ✞ struct list_Elem { 2 int data ; struct list_Elem *pointer ; 4 } ar [3]; 6 int main (int argc , char *argv []) {
  • 61. 3.3. DATA STRUCTURES 241 ar [0]. data = 5; 8 ar [0]. pointer = &ar [1]; ar [1]. data = 99; 10 ar [1]. pointer = &ar [2]; ar [2]. data = -7; 12 ar [2]. pointer = 0; /* mark end of list */ return (0); 14 } ✌ ✆ and the contents of the list can be printed in two ways. The array can be traversed in order of index, or the pointers can be used as in the following example. ✞ #include <iostream > 2 using namespace std; 4 struct list_Elem { int data ; 6 struct list_Elem *pointer ; } ar [3]; 8 int main (int argc , char *argv []) { 10 struct list_Elem *lp; 12 ar [0]. data = 5; 14 ar [0]. pointer = &ar [1]; ar [1]. data = 99; 16 ar [1]. pointer = &ar [2]; ar [2]. data = -7; 18 ar [2]. pointer = 0; /* mark end of list */ 20 /* follow pointers */ lp = ar; 22 while (lp) { cout << "contents " << lp ->data << endl ; 24 lp = lp ->pointer ; } 26 return 0; } ✌ ✆ ✞ contents 5 contents 99 contents -7 ✌ ✆ Structure As Arguments A structure can also passed to a function as shown in the example below: ✞ 1 #include <iostream > using namespace std;
  • 62. 242 Accessing System Files 3 #define TREE_NUM 50 5 /* Structure for garden tree length.*/ 7 struct g_len { char gardens[TREE_NUM ]; 9 double t_len_1; double t_len_2; 11 }; 13 /* Structure passed to the function .*/ double sum(struct g_len val) { 15 return (val.t_len_1 + val.t_len_2 ); } 17 int main (int argc , char *argv []) { 19 /* Initialized the structure .*/ struct g_len sbi = { 21 "G DELHI", 6524.12 , 23 9458.87 }; 25 double s=sum(sbi); cout << "Tree length is " << s << endl ; 27 return 0; } ✌ ✆ ✞ Tree length is 15982.99 m. ✌ ✆ 3.3.2 Enumerate In C++, enumerations are created by explicit definitions, which use the enum keyword and are reminiscent of struct and union definitions. Point of declaration of enum is that point of the program body, where, enum list is started. See example below. ✞ 1 #include <iostream > using namespace std; 3 enum { 5 /*0*/ /*1*/ /*2*/ TRUE , FALSE , NO 7 } b = NO; 9 int main (int argc , char ** argv ) { cout << "bool : " << b << endl ; 11 return 0; } ✌ ✆
  • 63. 3.3. DATA STRUCTURES 243 ✞ bool : 2 ✌ ✆ C also allows the programmer to choose the values of the enumeration constants explicitly, even without type. ✞ 1 #include <iostream > using namespace std; 3 enum { 5 TRUE = 0, FALSE = 1, NO = 10 } b = NO; 7 int main (int argc , char ** argv ) { 9 cout << "bool : " << b << endl ; return 0; 11 } ✌ ✆ ✞ bool : 10 ✌ ✆ In enumerate the values are assigned successively. If any enum key is set to a specific value then next enum key has value one larger than its preceding enum key if its value is not set. ✞ 1 #include <iostream > using namespace std; 3 int main (int argc , char ** argv ) { 5 enum COLORS { 7 BLUE , /* Index value 0*/ GREEN = 3, /* Index value 3*/ 9 YELLOW , /* Index value 4*/ RED = 2, /* Index value 2*/ 11 BLACK /* Index value 3*/ }; 13 cout << "The colors are:n"; cout << BLUE << endl ; /*0*/ 15 cout << YELLOW << endl ; /*4*/ cout << BLACK << endl ; /*3*/ 17 return 0; 19 } ✌ ✆ ✞ The colors are: 0 4 3 ✌ ✆
  • 64. 244 Accessing System Files 3.3.3 Union The definition of a union is similar to that of a struct. The difference between the two is that in a struct, the members occupy different areas of memory, but in a union, the members occupy the same area of memory. Thus, in the following type, for example: ✞ union { 2 int i; double d; 4 } u; ✌ ✆ The programmer can access either ‘u.i’ or ‘u.d’, but not both at the same time. Since ‘u.i’ and ‘u.d’ occupy the same area of memory, modifying one modifies the value of the other, sometimes in unpredictable ways. The size of a union is the size of its largest member. A simple example is ✞ #include <iostream > 2 #include <string > using namespace std; 4 union Data { 6 int i; float f; 8 char str [50]; }; 10 int main (int argc , char ** argv ) { 12 union Data data ; data .i = 10; 14 data .f = 220.5; string str("C Programming "); 16 str.copy (data .str , str.length()); data .str[str.length ()]=’0’; 18 cout << "data .i : " << data .i << endl ; cout << "data .f : " << data .f << endl ; 20 cout << "data .str : " << data .str << endl ; return 0; 22 } ✌ ✆ ✞ data .i : 1917853763 data .f : 4.12236 e+30 data .str : C Programming ✌ ✆ A constructor and destructor member function can also be declared inside the union. union has few restrictions like 1. A union cannot have virtual functions, members of reference type and base classes. It cannot be used as a base class. 2. If a union has a member with a user-defined constructor, a copy operation, a move operation, or a destructor, then that special function is deleted for that union; that is, it cannot be used for an object of the union type.
  • 65. 3.4. MEMORY MANAGEMENT 245 3. At most one member of a union can have an in-class initializer. 3.4 Memory Management 3.4.1 Create Memory Space If there is requirement of a few bytes of memory to store data then we allocate memory space by using simple variables. But in case of array, string and stacks where addition of data is not static a dynamic memory allocation is required. Arrays, strings and stack stores non-counting data when a program is in run thus the memory size should be expanded when a new data is added. Allocation of memory while program is in run is called dynamic memory allocation. To create a dynamic memory space, we use new keyword for this purpose. Its syntax is ✞ 1 int *i = new int [10];/*A block of ten integers .*/ int *j = new int (10) ; /* Heap allocation for 10 integers .*/ ✌ ✆ The new returns the address of first element of the array to the pointer ‘i’. Each time a dynamic memory is created, must be freed before exit from the program by using delete keyword. ✞ delete i; ✌ ✆ ✞ 1 #include <iostream > using namespace std; 3 int main (int argc , char ** argv ) { 5 int *i = new int [5]; int j; 7 for (j = 0; j < 5; j++) { i[j] = j; 9 } 11 for (j = 0; j < 5; j++) { cout << i[j] << endl ; 13 } delete i; 15 return 0; } ✌ ✆ ✞ 0 1 2 3 4 ✌ ✆
  • 66. 246 Accessing System Files 3.4.2 Delete Memory Space Each memory heap created dynamically by new operator must be freed by using delete keyword. ✞ 1 #include <iostream > using namespace std; 3 int main (int argc , char ** argv ) { 5 int *i = new int [5]; // Create space for 5 integers delete i; // Clear the space 7 return 0; } ✌ ✆ 3.4.3 Placement Memory Space new() operator is used to place a memory space over the given buffer stack. For example, ‘b’ is declared as a buffer of two element. The new() operator ✞ int b[2]; 2 /* Create memory space and filled with 5*/ int *i = new(b) int (5); ✌ ✆ places a memory space over buffer and puts the integer value ‘5’. The address of this element is assigned to variable ‘i’. Similarly, ✞ 1 int *i = new(b + sizeof (int)) int (6); ✌ ✆ puts the integer value ‘6’ over the buffer at memory location 4 bytes (size of integer) ahead to the address of buffer ‘b’. See the example below: ✞ 1 #include <iostream > using namespace std; 3 int main () { 5 int b[2]; int *i = new(b) int (5); 7 int *j = new (b + sizeof (int)) int (6); cout << *i << endl ; 9 cout << *j << endl ; return 0; 11 } ✌ ✆ ✞ 5 6 ✌ ✆ Placements are not deallocated by using delete keyword.
  • 67. 3.5. STACK 247 3.5 Stack C++ has a ‘stack’ library which deals with all stack related activities. An stack is initiated as ✞ stack <int > myStack; /* For integer stack*/ 2 stack <float > myStack; /* For float stack*/ stack <string > myStack; /* For string stack*/ ✌ ✆ Stack is based on the Last In First Out (LIFO) principle. The last element inserted by push() function returns at first by pop() function. 3.5.1 Empty Stack empty() function tells whether a stack is empty or non empty. If stack is empty then it returns true otherwise returns false. ✞ 1 #include <iostream > #include <stack > 3 using namespace std; 5 int main (int argc , char ** argv ) { stack <int > myStack; 7 myStack .push (10) ; cout << myStack.empty() << endl ; /* Returns 0*/ 9 myStack .pop(); cout << myStack.empty() << endl ; /* Returns 1*/ 11 return 0; } ✌ ✆ ✞ 0 1 ✌ ✆ 3.5.2 Size of Stack size() function returns the size of the stack. ✞ #include <iostream > 2 #include <stack > using namespace std; 4 int main (int argc , char ** argv ) { 6 stack <int > myStack; myStack .push (10) ; 8 myStack .push (11) ; myStack .push (12) ; 10 cout << "Size of stack : "; cout << myStack.size () << endl ; /* Returns 3*/ 12 myStack .pop();
  • 68. 248 Accessing System Files cout << "Size of stack : "; 14 cout << myStack.size () << endl ; /* Returns 2*/ return 0; 16 } ✌ ✆ ✞ Size of stack : 3 Size of stack : 2 ✌ ✆ 3.5.3 Get Top Element top() returns the reference of topmost element of the stack. This function can replace the top most element or can do arithmetic on it if arithmetic operator is used. ✞ #include <iostream > 2 #include <stack > using namespace std; 4 int main (int argc , char ** argv ) { 6 stack <int > myStack; myStack .push (10) ; 8 myStack .push (11) ; myStack .push (12) ; 10 cout << "Size of stack before top () is : "; cout << myStack.size () << endl ; /* Returns 3*/ 12 myStack .top() = 10; cout << "Size of stack after top () is : "; 14 cout << myStack.size () << endl ;/* Returns 3*/ cout << "Top stack is : "; 16 cout << myStack.top () << endl ; /* Returns 10*/ myStack .top() -= 7; 18 cout << "Top stack is : "; cout << myStack.top () << endl ; /* Returns 3*/ 20 return 0; } ✌ ✆ ✞ Size of stack before top () is : 3 Size of stack after top () is : 3 Top stack is : 10 Top stack is : 3 ✌ ✆ 3.5.4 Add Element at Top push function is used to add an element into the stack. Its syntax is ✞ <stack name >. push (<value >); ✌ ✆
  • 69. 3.5. STACK 249 ✞ 1 #include <iostream > #include <stack > 3 using namespace std; 5 int main (int argc , char ** argv ) { stack <int > myStack; 7 myStack .push (10) ; myStack .push (11) ; 9 myStack .push (12) ; cout << "Top element is : "; 11 cout << myStack.top () << endl ; /* Returns 12*/ return 0; 13 } ✌ ✆ ✞ Top element is : 12 ✌ ✆ 3.5.5 Remove Top Element pop is used to remove the top of the element of a stack. It is used as ✞ 1 <stack name >. pop(); ✌ ✆ ✞ 1 #include <iostream > #include <stack > 3 using namespace std; 5 int main (int argc , char ** argv ) { stack <int > myStack; 7 myStack .push (10) ; myStack .push (11) ; 9 myStack .push (12) ; cout << "Top element is : "; 11 cout << myStack.top () << endl ; /* Returns 12*/ myStack .pop(); /* Remove top most element */ 13 cout << "Top element is : "; cout << myStack.top () << endl ; /* Returns 11*/ 15 return 0; } ✌ ✆ ✞ Top element is : 12 Top element is : 11 ✌ ✆
  • 70. 250 OOP in C++
  • 71. 4.1. STRUCTURES 251 4OOP in C++ 4.1 Structures In Object Oriented Programming, a structure is required. A struct is like a class except for the default access. C++ also support the C like structure. Structures are also allow Operator Overloading. A struct is defined as ✞ struct myStructType /*: inheritances */ { 2 public: <public memters > 4 protected : <protected members > 6 private : <private members > 8 } myStructName ; ✌ ✆ public members are accessed from anywhere by declaring structure object and calling public member. private members are accessed within the structure definition only, i.e. by member classes or member functions defined within the parent structure. protected members are accessible in the class or through derived classes. An object of type ‘myS- tructType’ is declared as ✞ myStructType <object name >; ✌ ✆ The simplest example of the struct is the structure for the coordinate point. A point structure is defined and initialized as ✞ 1 struct Point { double x, y; 3 }; ✌ ✆ In this definition of structure, there are two members named as x and y. We can set the values to the member of this structure as ✞ 1 struct Point blank; blank.x = 3.0; 3 blank.y = 4.0; ✌ ✆ We can read the values of an instance variable using the same syntax we used to write them: ✞ 1 int x = blank.x; ✌ ✆ See the example below:
  • 72. 252 OOP in C++ ✞ 1 #include <iostream > using namespace std; 3 struct Point { 5 double x, y; }; 7 int main (int argc , char *argv []) { 9 struct Point point; point.x = 1; 11 point.y = 1.5; cout << "x is " << point.x << " and y is " << point.y; 13 return 0; } ✌ ✆ ✞ x is 1 and y is 1.5 ✌ ✆ The detailed explanation is given in struct section. Size of struct is equal to the sum of sizes of its all variables. ✞ 1 #include <iostream > using namespace std; 3 struct A { 5 int i [30]; /*30 X 4= 120 bytes*/ int j [20]; /*20 X 4= 80 bytes*/ 7 };/* Total size is 200 bytes*/ 9 int main (int argc , char *argv []) { cout << "sizeof struct A = " << sizeof (A) 11 << " bytes" << endl ; return 0; 13 } ✌ ✆ ✞ sizeof struct A = 200 bytes ✌ ✆ struct can also holds the member function inside them. A member function inside the struct is modified by using operator ‘::’. The member function is accessed by calling struct and its member function. See the example below: ✞ 1 #include <iostream > using namespace std; 3 struct A { 5 void g();/* declaring member function */ }; 7 /* Accessing the member function g()* 9 *of structure A and modifing to it*/
  • 73. 4.1. STRUCTURES 253 void A::g() { 11 cout << "Sturcture A" << endl ; } 13 int main (int argc , char *argv []) { 15 /* Declare and initialized struct A*/ struct A a; 17 /* Call to memeber function g()*/ a.g(); 19 return 0; } ✌ ✆ ✞ Sturcture A ✌ ✆ Pointer can also be used in argument of a member function. A child structure alongwith its members can also be defined inside the parent structure. See the example below: ✞ 1 #include <iostream > using namespace std; 3 struct A { 5 /* declaring member function * *with pointer type argument */ 7 void g(int* x); 9 struct B { void h(); 11 }; }; 13 /* Accessing the member function g()* 15 *of structure A and modifing to it*/ void A::g(int* x) { 17 cout << "Sturcture A" << endl ; cout << "x is " << *x << endl ; 19 } 21 void A::B::h() { cout << "Nested struct !!"; 23 } 25 int main (int argc , char *argv []) { struct A a; 27 int i = 12; a.g(&i); 29 struct A::B b; b.h(); 31 return 0; } ✌ ✆
  • 74. 254 OOP in C++ ✞ Sturcture A x is 12 Sturcture A x is -12 ✌ ✆ Following example has a nested struct model. The nested model has member function h(). Function definition of this member function is defined outside the structure by using operator ‘::’. ✞ #include <iostream > 2 using namespace std; 4 /* Outer parent structure */ struct A { 6 void g(int* x); 8 /* Nested child structure */ struct B { 10 void h(); }; 12 }; 14 void A::g(int* x) { cout << "Sturcture A" << endl ; 16 cout << "x is " << *x << endl ; } 18 /* Accessing function of nested child B * 20 *structure and defining its definitions .*/ void A::B::h() { 22 cout << "Nested struct !!"; } 24 int main (int argc , char *argv []) { 26 struct A a; int i = 12; 28 a.g(&i); struct A::B b; 30 b.h(); return 0; 32 } ✌ ✆ ✞ Sturcture A x is 12 Nested struct !! ✌ ✆
  • 75. 4.2. CLASSES 255 4.2 Classes Classes are used to create user defined types which includes the set of functions. An instance of a class is called an object and programs can contain any number of classes. As with other types, object types are case-sensitive. A class can have both, the data members and the function members associated with it. A class is defined by: ✞ 1 class MyClass { /* public , protected and private * 3 * variables /constants /functions */ }; ✌ ✆ An object of MyClass class is declared as shown in the following syntax. ✞ MyClass object; ✌ ✆ By default, all class members are initially private unless they are declared as pro- tected or public. A class is like a container which contains is all members. ✞ 1 class MyClass { int x;// integer variable x 3 void f(){}// function with definition }; ✌ ✆ MyClass x void f() Figure 4.1: Fields/Members of a class. Remember that the memory arrangement of the class object is in different form. Non- virtual functions do not reflects in memory arrangement. (See Virtual Function Table (VFT) for details.) The object of a class can not access to private data members of own class but they can be accessed from within the class. ✞ #include <iostream > 2 using namespace std; 4 class A { int x = 1; 6 public: int y = 2; 8 void X(){
  • 76. 256 OOP in C++ cout << x << endl ; 10 } }; 12 int main () { 14 A *a = new A(); // cout << a->x;// Error!! accessing private member 16 cout << a->y << endl ; a->X(); // Return the value of private A::x 18 return 0; } ✌ ✆ ✞ 2 1 ✌ ✆ A x=1 y=2 X() a (object of A) x=1 y=2 X() In first part of above figure, all data members of the class ‘A’ are shown. In second part of above figure, object of class ‘A’ can not access private member ‘x’ directly but it can access to it via member function ‘X()’. If object of a class is declared twice then each object is created at different location of memory address. See in the example given below: ✞ #include <iostream > 2 using namespace std; 4 class Address { int HNo; 6 int BlockNo ; public: 8 void getLocality (); void getDistrict (); 10 void getState (); int pin; 12 }; 14 int main () { Address A, B; 16 cout << "Memory Address of object A is " << &A << endl ; cout << "Memory Address of object B is " << &B << endl ; 18 return 0;