Anda di halaman 1dari 157

Arrays

Array
Consecutive group of memory locations
Same name and type (int, char, etc.)

To refer to an element
Specify array name and position number
(index)
Format: arrayname[ position number ]
First element at position 0

N-element array c
c[ 0 ], c[ 1 ] c[ n - 1 ]

Nth element as position N-1

Arrays
Array elements like other variables
Assignment, printing for an integer array c
c[ 0 ] = 3;
cout << c[ 0 ];

Can perform operations inside subscript


c[ 5 2 ] same as c[3]

Ordinary variables are capable of holding only


one value at a time, however there are situations
we want to store more than one value in a single
variable name.

One dimensional array:


Data_type Array name [cont_int_exp];
float x[4]; //for elements of floating point type
Char [80]; //character array of 80 elements
x

Accessing individual components:


x[2]=9.81 //assign a value
cin >> x[2] //read a value
y=sqrt (x[2]); //pass it as arguments
A few types
Pointer-based arrays (C-like)
Arrays as objects (C++)

X[0]
X[1]

Lack of aggregate array operations

int x[50];
int y[50];
x=y; //not valid
for (int i=0; i<50; i++)
x[i]=y[i];
if (x= = y) //not valid
cout << x; // valid but gives the address of first element
x=x+y; //not valid
return x; //not valid

Declaring Arrays
When declaring arrays, specify
Name
Type of array
Any data type

Number of elements
type arrayName[ arraySize ];
int c[ 10 ]; // array of 10 integers
float d[ 3284 ]; // array of 3284 floats

Declaring multiple arrays of same type


Use comma separated list, like regular variables
int b[ 100 ], x[ 27 ];

Examples Using Arrays

Initializing arrays
For loop
Set each element

Initializer list
Specify each element when array declared
int n[ 5 ] = { 1, 2, 3, 4, 5 };
If not enough initializers, rightmost elements 0
If too many syntax error

To set every element to same value


int n[ 5 ] = { 0 };

If array size omitted, initializers determine size


int n[] = { 1, 2, 3, 4, 5 };

5 initializers, therefore 5 element array

Initialization
Global and static arrays are automatically initialized
to default values, i.e., pattern of 0's in all bits.
Arrays declared in local scope are not automatically
initialized
Initialization is possible at the time of declaration
as: int idata[5]={1, -1, 4, 2, -3};
The number of initialization data within { } should
not be greater than the declared size of array.

Initializing arrays

The dimension of the array can be omitted from


declaration if it is possible to get this information
from the initialization as: int jdat[ ]={1, -1, 4}; will
define an array of integers of size 3 and is
equivalent to: int jdat[3]={1, -1, 4};
It is permitted to have fewer initialization values
than the size of array. The specified values are
used to initialize the array elements from
beginning. The remaining elements are initialized
to 0.

Array initialization

int main ()
{
double a[4] = (22.2, 44.4, 66.6, 88.8);
for (int i = 0; i < 4; i++)
cout << a[i] << endl;
}

a[0] = 2 2 . 2
a[1] = 4 4 . 4
a[21 = 6 6 . 6
a[3] = 8 8 . 8

int main()
{
double a[4] = (22.2, 44.4);
for (int i = 0; i < 4; i++)
cout << a[i] << endl;
}
Output:

a[0] = 2 2 . 2
a[1] = 4 4 . 4
a[21 = 0.0
a[3] = 0.0

Int main()
const int size = 4;
double a[size];
cout << "Enter<< size<< real numbers:\n";
for (int i = 1; i <= size; i++) {
cout<< i ;
cin >> a[i-1];
cout << "Here they are in reverse order:\n";
for (i = size-l; i >= 0; i--)
cout << i << a[i] << endl;

The constant integer size is initialized with the value 4. It


is then used to declare the array a, to prompt the user,
and to control both for loops.

// Initializing an array to zero.

#include <iostream>

#include <iomanip>
int main()

int n[ 10 ]; // n is an array of 10 integers

// initialize elements of array n to 0

for ( int i = 0; i < 10; i++ )

n[ i ] = 0; // set element at location i to 0

cout << "Element" << setw( 13 ) << "Value" << endl;

// output contents of array n in tabular format

for ( int j = 0; j < 10; j++ )

cout << setw( 7 ) << j << setw( 13 ) << n[ j ] << endl;

return 0; // indicates successful termination

} // end main

Element

Value
0
0
0
0
0
0
0
0
0
0

// Initializing an array with a declaration.

#include <iostream>

#include <iomanip>

int main()

// use initializer list to initialize array n

int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };

cout << "Element" << setw( 13 ) << "Value" << endl;

// output contents of array n in tabular format

for ( int i = 0; i < 10; i++ )

cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl;

return 0; // indicates successful termination

} // end main

Output:
Element

Value
32
27
64
18
95
14
90
70
60
37

Examples Using Arrays


Array size
Can be specified with constant variable (const)
const int size = 20;
Constants cannot be changed
Constants must be initialized when declared
Also called named constants or read-only variables
Example:
int main ()
{
const int x; //error x must be initialized
X=7; //can not modify a const variables
return 0; //indicates successful termination
} //end main

// Initialize array s to the even integers from 2 to 20.

#include <iostream>

#include <iomanip>

int main()
{
// constant variable can be used to specify array size
const int arraySize = 10;
int s[ arraySize ]; // array s has 10 elements
for ( int i = 0; i < arraySize; i++ ) // set the values
s[ i ] = 2 + 2 * i;
cout << "Element" << setw( 13 ) << "Value" << endl;

// output contents of array s in tabular format

for ( int j = 0; j < arraySize; j++ )

cout << setw( 7 ) << j << setw( 13 ) << s[ j ] << endl;

return 0; // indicates successful termination

} // end main

Element
0
1
2
3
4
5
6
7
8
9

Value
2
4
6
8
10
12
14
16
18
20

// Compute the sum of the elements of the array.

#include <iostream>

int main()

const int arraySize = 10;

int a[ arraySize ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

int total = 0;

// sum contents of array a

for ( int i = 0; i < arraySize; i++ )

total += a[ i ];

cout << "Total of array element values is " << total << endl;

return 0; // indicates successful termination

} // end main

Examples Using Arrays

Strings
Arrays of characters
All strings end with null ('\0')
Examples
char string1[] = "hello";
Null character implicitly added
string1 has 6 elements

char string1[] = { 'h', 'e', 'l',


'l',
'o', '\0 };

Subscripting is the same


String1[ 0 ] is 'h'
string1[ 2 ] is 'l'

Input from keyboard


char string2[ 10 ];
cin >> string2;

Puts user input in string


Stops at first whitespace character
Adds null character

If too much text entered, data written beyond


array
Printing strings
cout << string2 << endl;
Does not work for other array types

Characters printed until null found

// Treating character arrays as strings.


#include <iostream>
int main()
{
char string1[ 20 ],
// reserves 20 characters
char string2[] = "string literal"; // reserves 15 characters
// read string from user into array string2
cout << "Enter the string \"hello there\": ";
cin >> string1; // reads "hello" [space terminates input]
// output strings
cout << "string1 is: " << string1 << "\nstring2 is: " << string2;

cout << "\nstring1 with spaces between characters is:\n";

// output characters until null character is reached

for ( int i = 0; string1[ i ] != '\0'; i++ )

cout << string1[ i ] << ' ';

cin >> string1; // reads "there"

cout << "\nstring1 is: " << string1 << endl;

return 0; // indicates successful termination

} // end main

Enter the string "hello there": hello there


string1 is: hello
string2 is: string literal
string1 with spaces between characters is:
hello
string1 is: there

Examples Using Arrays


Recall static storage
If static, local variables save values between
function calls
Visible only in function body
Can declare local arrays to be static
Initialized to zero
static int array[3];

If not static
Created (and destroyed) in every function call
we apply static to a local array declaration so the array is not
created and destroyed each time the program calls the function,
and the array is not destroyed each time the function terminates the
program.

// Static arrays are initialized to zero.


#include <iostream>
void staticArrayInit( void );
// function prototype
void automaticArrayInit( void ); // function prototype
int main()
{
cout << "First call to each function:\n";
staticArrayInit();
automaticArrayInit();
cout << "\n\nSecond call to each function:\n";
staticArrayInit();
automaticArrayInit();
cout << endl;
return 0; // indicates successful termination
} // end main

// function to demonstrate a static local array


void staticArrayInit( void )
{
// initializes elements to 0 first time function is called
static int array1[ 3 ];

cout << "\nValues on entering staticArrayInit:\n";


// output contents of array1
for ( int i = 0; i < 3; i++ )
cout << "array1[" << i << "] = " << array1[ i ] << " ";
cout << "\nValues on exiting staticArrayInit:\n";
// modify and output contents of array1
for ( int j = 0; j < 3; j++ )
cout << "array1[" << j << "] = "
<< ( array1[ j ] += 5 ) << " ";
} // end function staticArrayInit

// function to demonstrate an automatic local array


void automaticArrayInit( void )
{
// initializes elements each time function is called
int array2[ 3 ] = { 1, 2, 3 };

cout << "\n\nValues on entering automaticArrayInit:\n";


// output contents of array2
for ( int i = 0; i < 3; i++ )
cout << "array2[" << i << "] = " << array2[ i ] << " ";
cout << "\nValues on exiting automaticArrayInit:\n";
// modify and output contents of array2
for ( int j = 0; j < 3; j++ )
cout << "array2[" << j << "] = "
<< ( array2[ j ] += 5 ) << " ";
} // end function automaticArrayInit

First call to each function:


Values on entering staticArrayInit:
array1[0] = 0 array1[1] = 0 array1[2] = 0
Values on exiting staticArrayInit:
array1[0] = 5 array1[1] = 5 array1[2] = 5
Values on entering automaticArrayInit:
array2[0] = 1 array2[1] = 2 array2[2] = 3
Values on exiting automaticArrayInit:
array2[0] = 6 array2[1] = 7 array2[2] = 8

Second call to each function:


Values on entering staticArrayInit:
array1[0] = 5 array1[1] = 5 array1[2] = 5
Values on exiting staticArrayInit:
array1[0] = 10 array1[1] = 10 array1[2] = 10
Values on entering automaticArrayInit:
array2[0] = 1 array2[1] = 2 array2[2] = 3
Values on exiting automaticArrayInit:
array2[0] = 6 array2[1] = 7 array2[2] = 8

Passing Arrays to Functions


Specify name without brackets
To pass array myArray to myFunction
int myArray[ 24 ];
myFunction( myArray, 24 );

Array size usually passed, but not required


Useful to iterate over all elements

Arrays passed-by-reference
Functions can modify original array data
Value of name of array is address of first element
Function knows where the array is stored
Can change original memory locations
Individual array elements passed-by-value
Like regular variables
square( myArray[3] );

Passing Arrays to Functions


For functions to receive an array through a function call,
the functions parameter list must specify that the function
expect to receive an array.

Function prototype
void modifyArray( int b[], int arraySize );

Indicating that modifyArray expect to receive the


address of an array of integers in parameter b and
the number of array elements in parameter arraysize

// Passing arrays and individual array elements to functions.


#include <iostream>
#include <iomanip>

void modifyElement( int );

cout << "Effects of passing entire array by reference:"


<< "\n\nThe values of the original array are:\n";

void modifyArray( int [], int );

int main()
{
const int arraySize = 5;
// size of array a
int a[ arraySize ] = { 0, 1, 2, 3, 4 }; // initialize a

// output original array


for ( int i = 0; i < arraySize; i++ )
cout << setw( 3 ) << a[ i ];

cout << endl;


// pass array a to modifyArray by reference
modifyArray( a, arraySize );
cout << "The values of the modified array are:\n";
// output modified array
for ( int j = 0; j < arraySize; j++ )
cout << setw( 3 ) << a[ j ];
// output value of a[ 3 ]
cout << "\n\n\n"
<< "Effects of passing array element by value:"
<< "\n\nThe value of a[3] is " << a[ 3 ] << '\n';
// pass array element a[ 3 ] by value
modifyElement( a[ 3 ] );
// output value of a[ 3 ]
cout << "The value of a[3] is " << a[ 3 ] << endl;
return 0; // indicates successful termination
} // end main

// in function modifyArray, "b" points to the original array "a" in memory


void modifyArray( int b[], int sizeOfArray )

{
// multiply each array element by 2
for ( int k = 0; k < sizeOfArray; k++ )
b[ k ] *= 2;

} // end function modifyArray

// in function modifyElement, "e" is a local copy of


// array element a[ 3 ] passed from main
void modifyElement( int e )

{
// multiply parameter by 2
cout << "Value in modifyElement is "
<< ( e *= 2 ) << endl;

} // end function modifyElement

Effects of passing entire array by reference:


The values of the original array are:
0 1 2 3 4
The values of the modified array are:
0 2 4 6 8

Effects of passing array element by value:


The value of a[3] is 6
Value in modifyElement is 12
The value of a[3] is 6

Sorting array

Sorting data
Important computing application
Virtually every organization must sort some
data
Massive amounts must be sorted

Bubble sort (sinking sort)


Several passes through the array
Successive pairs of elements are compared
If increasing order (or identical), no change
If decreasing order, elements exchanged

Repeat these steps for every element

Example:
Go left to right, and exchange elements as
necessary
One pass for each element

Original: 3 4 2 7 6
Pass 1:
3 2 4 6 7 (elements exchanged)
Pass 2:
2 3 4 6 7
Pass 3:
2 3 4 6 7 (no changes needed)
Pass 4:
2 3 4 6 7
Pass 5:
2 3 4 6 7
Small elements "bubble" to the top (like 2 in this
example)

Swapping variables
int x = 3, y = 4;
y = x;
x = y;

What happened?

Both x and y are 3!


Need a temporary variable
Solution
int x = 3,
temp = x;
x = y;
y = temp;

y = 4, temp = 0;
// temp gets 3
// x gets 4
// y gets 3

// This program sorts an array's values into ascending


order.
#include <iostream>
#include <iomanip>

using std::setw;

int main()

{
const int arraySize = 10; // size of array a
int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
int hold; // temporary location used to swap array elements

cout << "Data items in original order\n";

// output original array


for ( int i = 0; i < arraySize; i++ )
cout << setw( 4 ) << a[ i ];

// bubble sort
// loop to control number of passes
for ( int pass = 0; pass < arraySize - 1; pass++ )

// loop to control number of comparisons per pass


for ( int j = 0; j < arraySize - 1; j++ )
// compare side-by-side elements and swap them if
// first element is greater than second element
if ( a[ j ] > a[ j + 1 ] ) {
hold = a[ j ];
a[ j ] = a[ j + 1 ];
a[ j + 1 ] = hold;
} // end if

cout << "\nData items in ascending order\


// output sorted array
for ( int k = 0; k < arraySize; k++ )
cout << setw( 4 ) << a[ k ];
cout << endl;
return 0; // indicates successful termination
} // end main

Data items in original order


2 6 4 8 10 12 89 68 45 37
Data items in ascending order
2 4 6 8 10 12 37 45 68 89

Unbound array
In some programming languages, an index variable will
not be allowed to go beyond the bounds set by the arrays
definition.

This security mechanism is not present in C++.


The array only has 5 elements. Once the index variable i
exceeds the value 4 in the functions for loop, the
reference a [ i ] is accessing memory cells that are not
part of the array. Their contents are unpredictable.
No indication from computer that anything wrong.

Two dimensional arrays (Matrix)


Data_type Array-name [const_int_exp][const_int_exp];
Multiple subscripts
a[ i ][ j ]
Tables with rows and columns
Specify row, then column

Row 0

Column 0
a[ 0 ][ 0 ]

Column 1
a[ 0 ][ 1 ]

Column 2
a[ 0 ][ 2 ]

Column 3
a[ 0 ][ 3 ]

Row 1

a[ 1 ][ 0 ]

a[ 1 ][ 1 ]

a[ 1 ][ 2 ]

a[ 1 ][ 3 ]

Row 2

a[ 2 ][ 0 ]

a[ 2 ][ 1 ]

a[ 2 ][ 2 ]

a[ 2 ][ 3 ]

Multiple-Subscripted Arrays
To initialize
Default of 0
Initializers grouped by row in braces

int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 }
};
Row 0
Row 1
Or Int b[2][2]={1,2,3,4};
1

int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };

Multiple-Subscripted Arrays
Referenced like normal
cout << b[ 0 ][ 1 ];

Outputs 0
Cannot reference using commas
cout << b[ 0, 1 ];

Syntax error

Function prototypes
Must specify sizes of subscripts
First subscript not necessary, as with singlescripted arrays

void printArray( int [][ 3 ] );

Sum of rows:
Example: int x[52][7]
Sum of 3rd row:
for (int i=0; i<7; i++)
Sum+=x[2][i];

Similarly, sum of 5th column:


for (int i=0; i<52; i++)
Sum+=x[i][4];

// Initializing multidimensional arrays.


#include <iostream>
void printArray( int [][ 3 ] );
int main()
{
int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } };
int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 };
int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } };
cout << "Values in array1 by row are:" << endl;
printArray( array1 );

cout << "Values in array2 by row are:" << endl;


printArray( array2 );
cout << "Values in array3 by row are:" << endl;
printArray( array3 );
return 0; // indicates successful termination
} // end main

// function to output array with two rows and three columns


void printArray( int a[][ 3 ] )
{
for ( int i = 0; i < 2; i++ ) { // for each row

Values in array1 by row are:


123
456
Values in array2 by row are:
123
450
Values in array3 by row are:
120
400

for ( int j = 0; j < 3; j++ ) // output column values


cout << a[ i ][ j ] << ' ';
cout << endl; // start new line of output
} // end outer for structure
} // end function printArray

Pointers
When we say a certain variable is pointer.
What does it mean?
A pointer is a variable which holds the memory
address of another variable.
Pointer notation:
consider
int i=3;
This declaration tells the compiler
Reserve space in memory to hold the integer value.
Associate the name i with this memory location
Store the value 3 at this location.

Location name

i
3
6485

Value at location
Location number

The address of i in memory is a number.


We can print the address number as:
main()
{
int i=3;
cout << address of i << &i<<endl;

}
Output:
Address of i=6485
& is used in the statement is a address operator.

Pointer operator:
A pointer operator is represented by a combination of
* (asterisk) with a variable.
If a variable of integer data type and also declared
*(asterisk) with another variable, it means the variable is
of type pointer to integer. It will be used in the program
indirectly to access the value of one or more integer
variables.
Example: int *ptr
Where ptr is a pointer variable which holds the address of an
integer data type.
All pointer variables must be declared before it is used in
the program like other variable.

The general format:


data_type *pointer_variable.
Example:
float *fpointer;
double *dpoint;
char *mpoint1;
The base type of the pointer indicates the type of variable
the pointer is pointing to.
All pointer arithmetic is done relative to its base type. Hence
it is important to declare pointer correctly.

Address operator:
An address operator is represented by a combination of &
(ampersand) with a pointer variable.
If a pointer variable is an integer type and also declared &
with the pointer variable, then it means that the variable
is of type address of.
The & is a unary operator that returns the memory address
of its operand.
Example:
m=&ptr
The above statements means that m receives the address
of ptr.
ptr
3

6485

m
6485

3276

int *m
It stands for value at address i.e. 3.
Pointer expression:
A pointer is a variable data type and hence the general rule
to assign its value to the pointer is same as that of any
other variable data type.
Example: int x, y
int *ptr1, *ptr2
ptr1=&x; //the memory address of x is assigned to ptr1
y=*ptr1; //the contents of the pointer variable ptr1 is
assigned to variable y.
ptr1=ptr2 //the address of ptr1 is assigned to ptr2.


1.

Some invalid pointer declaration:

int x;
int x_pointer; //declaration must have the prefix of *.
x_pointer =&x;
2. float y;
float *y_pointer;
y_pointer =y //the address operator have to use with y.
3. int x;
char *c_pointer;
c_pointer = &x; //mixed type is not permitted

Program to display contents of the pointer:


#include <iostream>
int main ()
{
int x;
int *ptr;
X=10;
Ptr=&x;
cout << x<<ptr <<endl;
cout << x<< *ptr<<endl;
}
Out put:
X=10, ptr=0x24ccff4
X=10, *ptr=10

Swapping using pointer:


int main ()
{
int a=10, b=20;
swapr (&a, &b);
cout <<a<<b<<endl;
}
swapr(int *x, int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}
Out put: a=20, b=10

To assign the pointer variable to another pointer


#include <iostream>
int main ()
{
int x;
int *ptr1;
int *ptr2;
x=10;
ptr1=&x;
ptr2=ptr1;
cout <<value of x= <<x<<endl;
cout << contents of ptr1= <<*ptr1<<endl;
cout <<contents of ptr2= <<*ptr2<<endl;
Output:
Value of x=10
Contents of ptr1=10
Contents of ptr2=10

Pointer arithmetic
As a pointer holds the memory address of a variable,
arithmetic operators can be used with pointers eg. +, -,
++, --.
Pointers are variables. They are not integers . But can be
displayed as unsigned integers.
Ptr++ causes the pointer to be incremented but not by 1.
Ptr-- causes the pointer to be decremented but not by 1.
Example:
Int value, *ptr;
Value=120
Ptr=&value; //let the value is 2000
Ptr++;
Cout <<ptr <<endl;
The program will display 2002.

In the case of pointers to character, the increment


and decrement appears to follows normal
arithmetic.
All pointers increase or decrease the length of the
data type they point to.
Assume 1 byte characters and 2 byte integers.
When a character pointer is incremented, its value
is increased by 1, however for integer it is 2.
Example:
ptr2=ptr1+6; //pointer directing to integer
If the memory address of ptr1 is 3200 and integer
value 6 is added so the resultant address is 3212.

Display the contents of pointer variable


#include <iostream>
int main ()
{
int x,y;
int *ptr;
x=10;
ptr=&x;
cout <<value of x= <<x<<pointer=<<*ptr <<endl;
y=*ptr+1;
cout <<value of y= <<x<<pointer=<<*ptr <<endl;
}
Output:
Value of x=10 pointer=10
Value of y=11 pointer =10

No other arithmetic operations are allowed other than


addition and subtraction with pointers on integers.
Pointers are not permitted following arithmetic
operations:
To multiply or divide.
To operate the bitwise shift
To add or subtract type float or type double to pointers.

Calling Functions by Reference

Pass-by-reference with pointer arguments


Simulate pass-by-reference
Use pointers and indirection operator

Pass address of argument using & operator


Arrays not passed with & because array name
already pointer
* operator used as alias/nickname for variable
inside of function

// Cube a variable using pass-by-reference


#include <iostream>
void cubeByReference( int * ); // prototype
int main()
{
int number = 5;
cout << "The original value of number is " << number;
// pass address of number to cubeByReference
cubeByReference( &number );
cout << "\nThe new value of number is " << number << endl;
return 0; // indicates successful termination
} // end main

// calculate cube of *nPtr; modifies variable number in


main
void cubeByReference( int *nPtr )

{
*nPtr = *nPtr * *nPtr * *nPtr; // cube *nPtr

} // end function cubeByReference


Output:
The original value of number is 5
The new value of number is 125

Using const with Pointers

const qualifier
Value of variable should not be modified
const used when function does not need to
change a variable

Four ways to pass pointer to function


Nonconstant pointer to nonconstant data
Highest amount of access

Nonconstant pointer to constant data


Constant pointer to nonconstant data
Constant pointer to constant data
Least amount of access

// Converting lowercase letters to uppercase letters


// using a non-constant pointer to non-constant data.
#include <iostream>
#include <cctype>

// prototypes for islower and toupper

void convertToUppercase( char * );


int main()
{
char phrase[] = "characters and $32.98";
cout << "The phrase before conversion is: " << phrase;
convertToUppercase( phrase );
cout << "\nThe phrase after conversion is: "
<< phrase << endl;
return 0; // indicates successful termination
} // end main

// convert string to uppercase letters


void convertToUppercase( char *sPtr )
{
while ( *sPtr != '\0' ) { // current character is not '\0'
if ( islower( *sPtr ) ) // if character is lowercase,
*sPtr = toupper( *sPtr ); // convert to uppercase
++sPtr; // move sPtr to next character in string
} // end while
} // end function convertToUppercase

The phrase before conversion is: characters and $32.98


The phrase after conversion is: CHARACTERS AND $32.98

Constant Pointers, Pointer Constants, and Constant


Pointer Constants
This fragment declares four variables: a pointer p, a
constant pointer cp, a pointer pc to a constant,
and a constant pointer cpc to a constant:

int * p;
++(*P);
++p;
int * const cp;
++ (*cp) ;
++cp;
const int * pc;
.++ (*pc) ;
++pc;
const int * const cpc;
++(*cpc);
++cpc;

// a pointer to an int
// ok: increments int *p
// ok: increments pointer p
// a constant pointer to an int
// ok: increments int *cp
// illegal: pointer cp is
constant
// a pointer to a constant int
// illegal: int *pc is constant
// ok: increments pointer pc
// a constant pointer to a
constant int
// illegal: int *cpc is constant
// illegal: pointer cpc is
constant

Note that the reference operator * may be used in a


declaration with or without a space on either side. Thus,
the following three declarations are equivalent:
int* p; // indicates that p has type int* (pointer to int)
int * p; // style sometimes used for clarity
int *p; // old C style

Access the array elements using pointers

int main()
{
int num[]={24,34,12,44,56,17};
int i, *j
j=&num[0]; //assign address of zeroth element
for (i=0; i<=5; i++)
{
cout <<address=<<j<<endl;
cout <<element=<<*j<<endl;
j++; //increment pointer to point to next location
}
}

Output:
Address=4001 element=24
Address=4003 element=34
Address=4005 element=12
Address=4007 element=44
Address=4009 element=56
Address=4011 element=17

Passing an entire array to a function


int main ()
{
int num []={24,34, 12, 44, 56,17};
display (&num[0],6); //address of zeroth element passed
}
display(int *j, int n)
{
Int i;
for (i=0; i<=n-1; i++)
{
cout <<*j<<endl;
j++; //increment pointer to point to next location
}
}
This two function are same:
display(&num[0],6);
display (num,6);

int num[]={24,34,12,44,56,17}
*num refer to the zeroth element of the array, i.e. 24
Similarly *(num+1) refer to first element of the array, i.e 34.
Following notation are same:
num[i]
*(num+i)
*(i+num)
i[num]
Accessing array element in different ways:
int main()
{
int num[]={24,34,12,44,56,17};
int i

for (i=0; i<=5; i++)


{
cout <<address= &num[i]<<endl;
cout <<element= <<num[i]<< *(num+i)<<endl;
cout <<*(i+num)<<i[num];
}
}
Output:
Address=4001 element=24 24 24 24
Address=4003 element=34 34 34 34
Address=4005 element=12 12 12 12
Address=4007 element=44 44 44 44
Address=4009 element= 56 56 56 56
Address=4011 element=17 17 17 17

Pointer to 2-D array


To access array element of a 2-D array using pointer:
int s[4][2] can be thought of setting up a 1-D array of 4
element, each of which is a 1-D array of 2 elements long.
We can imagine s to be an 1-D array then we refer to its
zeroth element as s[0].
Example:
Int main ()
{

int s[4][2]={

{1234, 56}

{1212, 33}

{1434, 80}

{1312, 78}
}

int i;
for (i=0; i<=3, i++)

cout << address of <<i<<th 1-D array<<&s[i]<<endl;


}

Output:
Address of 0 th 1-D
Address of 1 th 1-D
Address of 2 th 1-D
Address of 3 th 1-D

array=5002
array=5006
array=5010
array=5014

Suppose we want to refer to element s[2][1] using pointers.


We know s[2] would give address 5010, the address of
second 1-d array. (5010+1) would give address 5012. The
value at this address can be obtained by *(s[2]+1).
Following expressions are for same element:
s[2][1]
*(s[2]+1)
*(*(s+2)+1)
Example:
int main ()
{
int s[4][2]={
{1234, 56},
{1212, 33}
{1434, 80}
{1312, 78}
};

Int I, j;
for {i=0; i<=3; i++)
{
for (j=0; j<=1; j++)
cout << *(*(s+i)+j))<<endl;
}
}
Output:
1234 56
1212 33
1434 80
1312 78

Array of pointers
There can be array of pointers similar to array of ints or
array of floats.
Since a pointer variable always contains an address, an
array of pointers is a collection of addresses.
Example:
int main ()
{
int *arr[4]; //array of integer pointers
int i=31, j=5, k=19, l=71, m;
arr[0]=&i;
arr[1]=&j;
arr[2]=&k;
arr[3]=&l;

for (m=0; m<=3; m++)


cout << *(arr[m]));
}
Arr contains addresses of isolated variables I, j, k,l. The
for loop picks up the addresses present in arr and prints
the values present at these addresses.

Pointers in string operation


Many string operation in C++ are usually performed by
using pointers to the array as strings tend to be
accessed strictly in sequential order.
Example:
int main ()
{
char name [] =Klinsman;
char *ptr;
ptr=name; //store base address of string
while (*ptr!=\0)
{
cout <<*ptr<<endl;
ptr++
}
}

The character array elements can be accessed exactly


the same way as the elements of an integer array.
Following notations refer to the same element:
name[i]
*(name+i)
*(i+name)
i[name]

Array of pointers to string


A pointer variable always contains an address. Therefore
an array of pointers contain a number of addresses.
example:
char *names[]={
akshay;
parag;
raman;
srinivas;
gopal;
rajesh;
};
In this declaration names [] is an array of pointers.

Two dimensional array of character


Like 2-D array of integer we can have array of character.
Example:
#define FOUND 0
#define NOTFOUND 1
int main ()
{
char masterlist [6][10]={
akshay;
parag;
raman;
srinivas;
gopal;
rajesh;
};

int i, flag, a;
char yourname [10];
cout <<enter your name<<endl;
cin >>yourname;
flag=NOTFOUND
for (i=0; i<=5; i++)
{
a=strcmp (&masterlist[i][0], yourname)
if (a==0)
{
cout <<welcome <<endl;
flag=FOUND;
break;
}
}

if (flag==NOTFOUND)
cout <<sorry, you are not allowed<<endl;
}
Output:
Enter your name dinesh
Sorry, you are not allowed
Enter your name raman
Welcome
The first subscript gives the number of names in the array,
while the second subscript gives the length of each item
in the array.

Note that while comparing the strings through strcmp(),


the address of the strings are being passed to strcmp.
If the two strings match, strcmp () would return a value 0,
otherwise return non zero value.
The variable flag is used to keep a record of whether the
control did reach inside the if or not.
At begin set flag to NOTFOUND. Later through the loop if
the name match, flag is set to FOUND.
When the control reaches beyond the for loop, if flag is
still set to NOTFOUND, it means that none of the names
in the masterlist[][] matched with the one supplied from
the keyboard.

// Exchange names using 2-D array of character


int main()
{
char names [][10]={
akshay;
parag;
raman;
srinivas;
gopal;
rajesh;
};

int I;
char t;
cout <<original:<<&name[2][0]<<&name[3][0]<<endl;
For (i=0; i<=9; i++)
{

t=names[2][i];

names[2][i]=names[3][i];

names[3][i]=t;

}
cout <<new:<<&names[2][0]<<&names[3][0]<<endl;
}
Output:
Original: raman srinivas
New: srinivas raman
To exchange the names we are required 10 exchange corresponding
characters of the two names.

Number of exchanges can be reduced using an array of


pointers to strings
Int main ()
{

char *names[]={

akshay;
parag;
raman;
srinivas;
gopal;
rajesh;
};

char *temp;
cout <<Original: <<names [2]<<names[3]<<endl;
temp=names[2];
names[2]=names[3];
names[3]=temp;
cout <<New:<<names[2]<<names[3]<<endl;
}
Output:
Original: raman srinivas
New: srinivas raman

In this program all that we required to do is to exchange the addresses


(of the names) stored in the array of pointers rather than the names
themselves.
This makes string handling very convenient and efficient memory
usage.

POINTERS TO POINTERS

A pointer may point to another pointer. For


example,
char c = 't';
char* pc = &c;
char** ppc = &pc;
char*** pppc = &ppc;
***pppc = w; // changes the value of c to w
The assignment * **pppc = w refers to the
contents of the address PC that is pointed to
by the address ppc that is pointed to by the
address pppc.

Pointers to function
Every type of variable, with the exception register, has an
address.
We have seen how we can reference variables of type
char, int , float etc through their address.
Pointer can also point to functions like array as the
functions address we can point to it, which provides
another way to invoke it.
Example: //To get address of a function
int main ()
{
int display()
cout <<address of function display is = <<display<<endl;
display();
}

display()
{
cout <<welcome to pointer<<endl;
}
Output the program is
Address of the function display is 1125
Welcome to pointer

Note that to obtain the address of a function all that we


have to do is to mention the name of the function as we
have done in the array to get its base address.

Example:// invoking function using pointer to a function.


Int main()
{
int display();
int (*func_ptr)();
func_ptr=display; //assign address of function
cout <<address of function display is <<func_ptr<<endl;
(*func_ptr)(); //invokes the function display()
}
display()
{
cout << welcome to pointer<<endl;
}
Output:
Address of function display is 1125
Welcome to pointer

In the main we have declared the function display () as a


function returning an int.
We have again mention

func_ptr=display;
So the func_ptr is being assigned the address of display()
Therefore, func_ptr must be a pointer to the function
display().
int (*func_ptr)();
The above declaration means that func_ptr is a pointer to
a function, which returns an int.
And to invoke the function we required to write the
statement,
(*func_ptr)();

Example: The Sum of a Function


The sum() function has two parameters: the
function pointer pf and the integer n:
int sum (int (*) (int), int);
int square(int);
int cube(int);
int main(){
cout << sum(square,4) << endl; //1+4+9+16
cout << sum(cube,4) << endl; // 1 + 8 + 27 + 64
}

Here are the function definitions and the output:


// Returns the sum f(0) + f(1) + f(2) + . . . + f(n-1):

int sum(int (*pf)(int k), int n)


{
int s = 0;
for (int i = 1; i <= n; i++)
s += (*pf) (i);
return s;
}
int square(int k)
{
return k*k;
}
int cube(int k)
{
return k*k*k;
}

The sum ( ) function evaluates the function to which pf


points, at each of the integers 1 through n, and returns
the sum of these n values.
Note that the declaration of the function pointer
parameter pf in the sum ( ) functions parameter list
requires the dummy variable k.
The call sum(square,4) computes and returns the sum
square(l) + square(2) + square(3) + square (4 ) .
Since square (k) computes and returns k*k, the sum ( )
function returns 1 + 4 + 9 + 16 = 30.

References
A reference is an alias, a synonym for another variable. It is
declared by using the reference operator & appended to
the references type.
Example:
int main ()
int n = 33;
int& r = n; // r is a reference for n
cout << "n = << n << r = << r << endl;
- -n
cout << "n =<< n << r = << r << endl;
r *= 2;
cout<< n = << n << "r = << r << endl;

Output:
n=33 r=33
n=32 r=32
n=64 r=64
The two identifiers n and r are different names for the
same variable: they always have the same value.
Decrementing n changes both n and r to 32. Doubling r
increases both n and r to 64.

References are alias:


This shows that r and n have the same memory address:
int main ()
int n = 33;
int& r = n;
cout << "&n = << &n << &r = << &r << endl;

Output:
&n = 0x3fffdl4 &r = 0x3fffdl4

The value 33 is stored only once. The identifiers


n and r are both symbolic names for the same
memory location 0x3fffd14.

Like a const, a reference must be initialized when it is


declared.
when used as a prefix to a variable name, it returns the
address of that variable;
when used as a suffix to a type in a variable declaration, it
declares the variable to be a synonym for the variable to
which it is initialized;
when used as a suffix to a type in a functions parameter
declaration, it declares the parameter to be a reference
parameter for the variable that is passed to it.
All of these uses are variations on the same theme: the
ampersand refers to the address at which the value is
stored.

Dynamic memory allocation


Dynamic memory allocation enables a program to obtain
more memory at the execution time to hold new nodes.
When that memory is no longer needed by the program,
the memory can be released so that it can be reused to
allocate other object in future.
The limit of dynamic memory allocation can be as large
as the amount of available physical memory in the
computer or the amount of available virtual memory in a
virtual memory system.

Dynamic Memory Allocation

global or local variables constitute static data.


space is allocated for them at compile time.
the static space has a name named space.
dynamic space on the other hand is allocated at run time
dynamic space has no name anonymous space
it is accessible through a pointer only
A pointer can be initialized to point to the anonymous
memory space allocated at run time
advantage of dynamic space - order as much as the
need. Thus, more efficient utilization of memory
space
dynamic space handling makes use of new and delete
operators
space allocated through new can be returned through
delete only

Dynamic memory allocation


Two operators, namely new and delete are used in
dynamic memory allocations.
new: The new operator is used to create a heap of
memory space for an object of a class.
In C language there are special functions to create a
memory space dynamically, viz. malloc(), calloc() and
alloc().
The operator new calls upon the function operator new()
to obtain storage.
An allocation expression must carry out the following
three things
Find storage for the object to be created
Initialize that object and
Return a suitable pointer type to the object.

new operator

When a pointer is declared like this:


float* p; // p is a pointer to a float
it only allocates memory for the pointer itself.
The value of the pointer will be some memory address,
but the memory at that address is not yet allocated. This
means that storage could already be in use by some other
variable. In this case, p is uninitialized: it is not pointing to
any allocated memory.
Any attempt to access the memory to which it points will
be an error:
*p = 3.14159; // ERROR: no storage has been allocated
for *P

A good way to avoid this problem is to initialize pointers


when they are declared:
float x = 3.14159; // x contains the value 3.14159
float* p = &x; // p contains the address of x
cout << *p; // OK: *p has been allocated
In this case, accessing *p is no problem because the
memory needed to store the float 3.14159 was
automatically allocated when x was declared; p points to
the same allocated memory.

Another way to avoid the problem of a dangling pointer is


to allocate memory explicitly for the pointer itself. This is
done with the new operator:
Pointer-variable=new data_type;
float* q;
q = new float; // allocates storage for a float
*q = 3.14159; // OK: *q has been allocated
The new operator returns the address of a block of $
unallocated bytes in memory, where $ is the size of a
float.
(Typically, sizeof ( float > is 4 bytes.) Assigning that
address to q guarantees that *q is not currently in use by
any other variables.

The first two of these lines can be combined, thereby


initializing q as it is declared:
float* q = new float;
Note that using the new operator to initialize q only
initializes the pointer itself, not the memory to which it
points. It is possible to do both in the same statement that
declares the pointer:
float* q = new float(3.14159);
cout << *q; // ok: both q and *q have been initialized
In the unlikely event that there is not enough free memory
to allocate a block of the required size, the new operator
will return 0 (the NULL pointer):

double* p = new double;


if (p == 0) abort(); // allocator failed: insufficient memory
else *p = 3.14159;
This prudent code calls an abort ( > function to prevent
dereferencing the NULL pointer.
Consider again the two alternatives to allocating memory:
float x = 3.14159; // allocates named memory
float* p = new float(3.14159); // allocates unnamed memory
In the first case, memory is allocated at compile time to the
named variable X.
In the second case, memory is allocated at run time to an
unnamed object that is accessible through *p.

Delete operator
The delete operator reverses the action of the new
operator, returning allocated memory to the free store.
It should only be applied to pointers that have been
allocated explicitly by the new operator:
float* q = new float(3.14159);
delete q; // deallocates q
*q = 2.71828;
// Error: q has been deallocated
Deallocating q returns the block of sizeof ( float ) bytes to
the free store, making it available for allocation to other
objects.

Once q has been deallocated, it should not be used


again until after it has been reallocated.
A deallocated pointer, also called a dangling pointer, is
like an uninitialized pointer: it doesnt point to anything.
A pointer to a constant cannot be deleted:

const int * p = new int;


delete p; // Error: cannot delete pointer to const

This restriction is consistent with the general principle


that constants cannot be changed.
Using the delete operator for fundamental types (char,
int, float, double, etc.) is generally not recommended
because little is gained at the risk of a potentially
disastrous error:
float x = 3.14159; // x contains the value 3.14159
float* p = &x; // p contains the address of x
delete p; // Risky: p was not allocated by new
This would deallocate the variable X, a mistake that can
be very difficult to debug.

Example :
A program to create a dynamic memory allocation for the
standard data types: integer, floating point, character and
double.
The pointer variables are initialized with some data and
the contents of the pointer are display on the screen.
//Using new and delete operators
#include <iostream>
int main ()
{
int *ptr_i=new int (25);
float *ptr_f=new float (-10.1234);
char *ptr_c=new char (a);
double *ptr_d= new double(1243.57);

cout << contents of the pointer <<endl;


cout << integer = <<*ptr_i<< endl;
cout <<floating point value= <<*ptr_f<<endl;
cout << char= <<*ptr_c <<endl;
cout << double= <<*ptr_d <<endl;
delete ptr_i;
delete ptr_f;
delete ptr_c;
delete ptr_d;
}
Output:
Contents of the pointers
integer=25
floating point value=-10.1234
char=a
double=1243.57

Dynamic array
An array name is really just a constant pointer that is
allocated at compile time:
float a[20]; // a is a const pointer to a block of 20 floats
float* const p = new float[20]; // so is p
Here, both a and p are constant pointers to blocks of 20
floats.
The declaration of a is called static binding because it is
allocated at compile time; the symbol is bound to the
allocated memory even if the array is never used while
the program is running.
In contrast, we can use a non-constant pointer to
postpone the allocation of memory until the program is
running. This is generally called run-time binding or
dynamic binding:
float* p = new float[20];
An array that is declared this way is called a dynamic
array.

Compare the two ways of defining an array:


float a[20]; // static array .
float* p = new float[20]; // dynamic array
The static array a is created at compile time; its memory
remains allocated though out the run of the program.
The dynamic array p is created at run time; its memory
allocated only when its declaration executes.
Furthermore, the memory allocated to the array p is
deallocated as soon as the delete operator is invoked on
it:
delete [] p; // deallocates the array p
Note that the subscript operator [ ] must be included this
way, because p is an array.

Structure
Sometimes some logically related elements need to be
treated under one unit e.g. the elements storing a students
information (roll_no, name, class, marks, grade) needs to
be processed under one roof.
A structure is a collection of variables referenced under one
name.
Collection of one or more variables, possibly of different
types, under a single name for convenient handling.
Heterogeneous mixture of various data types
Each component has a name and is called a member
Member list is like a series of variable declarations
struct declaration is a type declaration for the whole
collection

The following code fragment shows how to define a


structure (say date). The keyword struct tells the compiler
that a structure is defined.
struct date {
short day;
short month;
short year;
};
The date is a structure tag and is identifies this particular
data structure and its type specifier.
No structure variable is being defined and hence no memory
space is reserved.
To declare a structure variable having the data form as
defined by date will be
date joining_date;

Structures
In general, a struct declaration looks like
struct <type name>
{
<Member list>;
} <variable list>;
The variables declared in variable list are of type <type
name>
Members of a struct can be struct themselves leading to
hierarchical structures.
Same member name can occur in different structs

Thus the complete structure definition is:


struct date{
short day;
short month;
short year;
};
date joining_date;
The above statement defines a structure type
called date and declares a structure variable
joining_date.
We can declare more structure variable in a
single declaration.
date joinjng_date, birth_date, retire_date;

Referring structure elements


Once a structure is defined, its member can be accessed
through the use of dot (.) operator.
e.g.
birth_date.year=1980;
The structure variable name followed by a period(.) and the
element name.
The structure member are treated as other variable.
cout << birth_date.year;
Cin >> joining_date.day>>joining_date.month>>joining_date.year;

Example:
#include <iostream>
int main ()
{
struct sample {
int x;
float y;
};
struct sample a;
a.x=10;
a.y=20.2;
cout << content of x= <<a.x <<endl;
cout << content of y= <<a.y <<endl;
Output:
Content of x=10;
Content of y=20.2

Initializing structure element


A structure can be initialized in the same way as any other data type in
c++.
example:
#include <iostream>
int main ()
{
struct school {
int rollno;
int age;
char sex;
float height;
float weight;
};
school student = {95001, 24, M, 167.9, 56.7};
cout << contents of structure \n;
cout << rollno = <<student.rollno <<endl;
cout << Age = <<student.age <<endl;

cout << sex= << student.sex<<endl;


cout << Height = <<student.height <<endl;
cout << weight = <<student.weight <<endl;
}
Out put:
Contents of structure
Rollno=95001
Age=24
Sex=M
Height=167.9
Weight=56.7

Nested structure
An element of a structure may even be an array or a structure itself.
A structure can be nested inside another structure.
Struct addr
//structure tag
{ int houseno;
char area[26];
char city[26];
char state[26];
};
struct emp
//structure tag
{ int empno;
char name[26];
char desig [16];
addr address;
float basic;
};
emp worker;
//create structure variable

Nested structure
The structure emp has been defined having several
elements including a structure address also.
The element address (of structure emp) is itself a structure
of type addr.
While defining such structure, the inner structure should be
defined before outer structure.
Accessing nested structure members:
The member of structure are accessed using dot operator.
To access the city member of address structure which is an
element of another structure worker,
We will write: worker.address.city
To initialize houseno member of address structure, element of
worker structure:
worker.address.houseno=889

#include <iostream>
#include <stdio.h>
Struct addr
//Global definition
{ int houseno;
char area[26];
char city[26];
char state[26];
};
struct emp
{ int empno;
char name[26];
char desig [16];
addr address; //another structure
float basic;
};
emp worker;
//create structure variable
int main ()

{
cout <<\n <<enter employee no <<endl;
cin >> worker.empno>>endl;
cout <<\n <<name<<endl;
gets (worker.name); //to read white spaces also as >> cant read
cout << \n <<Designation<<endl;
gets (worker.desig);
cout <<\n <<enter address <<endl;
cout <<house no <<endl;
cin >> worker.address.houseno >>endl;
cout << worker basic<<endl;
cin >> worker.basic;
return 0;
}
To initialize a nested structure at the time of declaration, as follows:
Emp worker={1085, sandeep, manager, {777, Tnagar, delhi,
delhi, 9800};

Arrays of structures
An array is a group of identical data which are stored in a common
heading. A similar type of structure placed in a common heading or a
common variable name is called arrays of structures.
e.g. To process the students particulars for the entire school
struct school {
int rollno;
int age;
char sex;
float height;
float weight;
};
school student [300];
The student is a structure variable. It may accommodate the structure of
300 student.

example:
#include <iostream>
#define MAX 3
Int main ()
{
struct school {
long int rollno;
int age;
char sex;
float height;
float weight;
};
scool student [MAX]= {
{ 95001, 24, M, 167.9, 57.6 },
{ 95002, 25, F, 156.9, 45 },
{ 95003, 27, M, 187.9, 78}
};
for (int i=0; i<=MAX-1; ++i) {

cout << contents of structure= <<i+1<<endl;


cout << Rollno= <<student[i].rollno<<endl;
cout << Age= <<student[i].age<<endl;
cout << sex= << student[i].sex <<endl;
cout << height=<< student[i].height <<endl;
cout << weight= << student[i].weight <<endl;
cout <<endl;
}
}
Output:

Content of structure =1

Rollno=95001
Age=24
Sex=M
Height =187.9
Weight= 78

Content of structure=2

Rollno=95002
Age=25
Sex=F
Height = 156.9
Weight= 45

Content of structure =3

Rollno=95003
Age=27
Sex=M
Height = 156.9
Weight= 45

Using Structures with Functions


Two ways to pass structures to functions
Pass entire structure
Pass individual members
Both pass call-by-value
To pass structures call-by-reference
Pass address
Pass reference to structure
To pass arrays call-by-value
Create structure with array as member
Pass the structure
Pass-by-reference more efficient

Passing structure elements to functions:


example:
struct date {
short day;
short month;
short year;
} Bdate;
Individual elements of this structure can be passed as
follows:
func1(Bdate.day, Bdate.month, Bdate.year);
The above function call invokes a function , func1 () by
passing values of individual structure elements of
structure Bdate.

Example: Pass by value and pass by reference


int main()
{
struct book
{
char name[25];
char author[25]
int callno;
};
struct book b1={ let us c++, YPK, 101};
display(b1.name, b1.author, b1.callno);
}
display(char *s, char*t, int n)
{
cout<<s<<t<<n<<endl;
}
Output:
Let us c++, YPK 101

In the declaration of the structure, name and author have


been declared as arrays.
Therefore, when we call the function display() using display
(b1.name, b1.author, b1.callno); we are passing the
addresses of the arrays name and author, but the value
stored in callno.
Thus, this is a mixed call; a call by reference as well as a
call by value.
To pass individual elements would become more tedious as
the number of structure elements go on increasing.
A better way would be to pass the entire structure variable
at a time.

Example:

struct book
{
char name [25];
char author [25];
int callno;
};
int main()
{
struct book b1={let us c++, YPK, 101};
display (b1);
}
display (struct book b)
{
cout << b.name<<b.author<<b.callno<<endl;
}
Out put:
Let us c++ YPK 101

In the previous example how to define formal arguments


in the function display()?
we can not say
struct book b1;
because the data type struct book is not known to the
function display().
Therefore it becomes necessary to define the structure type
strcu book outsude main(), so that it becomes known to
all functions in the program.

Structure pointers
The way we can have a pointer to an int, or a pointer
pointing to a char, similarly we can have a pointer
pointing to a struct. A pointer can be used to hold the
address of a structure variable.
Example:
struct sample {
int x;
float y;
char s;
};
struct sample *ptr;
Where ptr is a pointer variable holding the address of the
structure sample and is having three members such as
int x, float y and char s.

The pointer structure variable can be accessed and


processed as
(*strcuture_name).field_name=variable;
The parentheses are essential because the structure
member period(.) has a higher precedence over the
indirection operator (*).
The pointer to structure can also be expressed using -> sign.
structure_name->field_name=variable;
The lhs is a pointer to a structure.
Example:
int main()
{
struct sample {
int x;
float y;
char s;

struct sample *ptr;


(*ptr).x=10
(*ptr).y=-23.45
(*ptr).s=d
---}
Example:
#include <iostream>
int main ()
{
struct sample {
int x;
float y;
char s;
};

struct sample *ptr;


ptr ->x=10;
ptr ->y=-23.45;
ptr ->x=d;
----}
Example: To assign some value to the member of a
structure using an introduction operator.
//pointer and structures
//method 1
#include <iostream>
int main()
{
struct sample {

int x;
int y;
};
sample *ptr;
sample one;
ptr=&one;
(*ptr).x=10;
(*ptr).y=20;
cout << contents of x= <<(*ptr).x <<endl;
cout << contents of y= <<(*ptr).y <<endl;
}
Output:
Contents of x=10
Contents of y=20

//Method 2:
#include <iostream>
int main()
{
struct sample {
int x;
int y;
};
sample one;
sample *ptr;
ptr=&one;
ptr->=10;
ptr->y=20;
cout <<contents of x= <<ptr->x<<endl;
cout <<contents of y= <<ptr->y<<endl;
}
Output:
Contents of x=10
Contents of y=20

Example: A program to read a set of values from the keyboard using


a pointer structure operator and to display the contents of the
structure on the screen
//method3
#include <iostream>
int main ()
{
struct sample {

int x;

int y;

};
sample *ptr;
cout <<enter value for x and y \n;
cin >>ptr->x>>ptr->y;
cout << contents of x= <<ptr->x <<endl;
cout << contents of y= <<ptr->y<<endl;
}

Example: A program to declare a pointer variable as a member of a


structure and to display the contents of the structure.
//method 4
#include <iostream>
Int main ()
{

struct sample {

int *ptr1;

float *ptr2;

};

sample *first;

int value1;

float value2;
value1=10;
value2=-20.02;

first ->ptr1=&value1;
first -> ptr2=&value2;
cout << contents of the first number= ;
cout << *first->ptr1<<endl;
cout <<contents of the second number= ;
cout <<*first->ptr2<<endl;
}
Output:
Contents of the first number=10
Contents of the second number=-20.02

The indirection operator is also used to assign the pointer variable to a


structure.
#include <iostream>
Int main ()
{
Struct sample {

int *ptr1;

float *ptr2;

};

sample *first;

int value1;

float value2;

-----
----- (*first).ptr1=&value1;
(*first).ptr2=&value2;
----- }

Unions
Union like structure a data type with a difference in the way
the data is stored and retrieved.
The union stores values of different types in a single
location.
The declaration and usage of union is same as structures.
Union holds only one value for one data type. If a new
assignment is made, the previous value is automatically
erased.
The symbolic representation of a union declaration is:
Union user_defined_name{

member 1;

member 2;

----
member n;

};

The keyword union is used to declare the union data


type. This is followed by a user_defined_name
surrounded by braces which describes the member of
the union.
Example:

union sample {

int first;

float second;

char third;

} one, two;
Where one, two are the union variables name similar to
data size of the sample.

Processing with union


A period operator is used in between the union variable name and
the field name.
Once a union type is defined, variables for the union data type can
be declared.
Example:

union value {

int ch;

double dd;

};

union value x;
Similar to structures, the dot (.) operator is used to access a unions
individual field.
x.ch;
x.dd;

typedef
The typedef is used to define new data items
that are equivalent to the existing data types.
Once a user defined data is declared, then
new variables, arrays, structures and so on
can be declared in terms of this new data
types.
The general format of the user defined data
types:
typedef dataype newtype.

Where typedef is a keyword for declaring the


new data items and data type is an existing data
type being converted to the new name.
e.g. typedef int integer;

typedef float real;

integer i,j;

real a,b;
The typedef is used in a program to make it
readable and portable.

Example:
#include <iostream>
int main ()
{
typedef int integer;
typedef float real;
typedef char character;
integer i,j;
character ch;
real a,b;
i=10;
j=30;
ch=m

a=-23.45;
b=34.89;
cout <<using typedef <<endl;
cout <<i= <<i <<\t;
cout <<j= <<j <<endl;
cout <<ch= <<ch <<endl;
cout <<a= << a<<\t;
cout <<b= <<b <<endl;
}
Output:
Using typedef
i=10 j=30
ch=m
a=-23.45 b=34.89

Anda mungkin juga menyukai