0% found this document useful (0 votes)
1 views19 pages

C++ Unit3 Chapter1

The document provides an overview of derived data types in C++, focusing on arrays, strings, and pointers. It explains one-dimensional and multi-dimensional arrays, their declarations, and traversal through example programs. Additionally, it covers string manipulation functions and the concept of pointers, including their declaration, initialization, and arithmetic operations.

Uploaded by

SushmaRaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views19 pages

C++ Unit3 Chapter1

The document provides an overview of derived data types in C++, focusing on arrays, strings, and pointers. It explains one-dimensional and multi-dimensional arrays, their declarations, and traversal through example programs. Additionally, it covers string manipulation functions and the concept of pointers, including their declaration, initialization, and arithmetic operations.

Uploaded by

SushmaRaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

C++ Programing Language 1

UNIT 3

DERIVED DATA TYPES

Arrays:

An array in C or C++ is a collection of items stored at contiguous memory locations and elements can be
accessed randomly using indices of an array. They are used to store similar types of elements as in the
data type must be the same for all elements. They can be used to store the collection of primitive data
types such as int, float, double, char, etc of any particular type. To add to it, an array in C or C++ can
store derived data types such as the structures, pointers, etc.
There are two types of arrays:

 One Dimensional Array

 Multi Dimensional Array

One Dimensional Array: A one dimensional array is a collection of same data types. 1-D array is
declared as:

data_type variable_name[size]

data_type is the type of array, like int, float, char, etc.

variable_name is the name of the array.

size is the length of the array which is fixed.

Note: The location of the array elements depends upon the data type we use.

Below is the illustration of the array:

Below is the program to illustrate the traversal of the array:

// C++ program to illustrate the traversal

// of the array

#include "iostream"

Sushma B | JSSCACS| 2024-25


C++ Programing Language 2

using namespace std;

// Function to illustrate traversal in arr[]

void traverseArray(int arr[], int N)

// Iterate from [1, N-1] and print

// the element at that index

for (int i = 0; i < N; i++) {

cout << arr[i] << ' ';

// Driver Code

int main()

// Given array

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

// Size of the array

int N = sizeof(arr) / sizeof(arr[0]);

// Function call

traverseArray(arr, N);

OUTPUT:

1234

MultiDimensional Array: A multidimensional array is also known as array of arrays. Generally, we use
a two-dimensional array. It is also known as the matrix. We use two indices to traverse the rows and
columns of the 2D array. It is declared as:

data_type variable_name[N][M]

Sushma B | JSSCACS| 2024-25


C++ Programing Language 3

data_type is the type of array, like int, float, char, etc.

variable_name is the name of the array.

N is the number of rows.

M is the number of columns.

Below is the program to illustrate the traversal of the 2D array:

// C++ program to illustrate the traversal

// of the 2D array

#include "iostream"

using namespace std;

const int N = 2;

const int M = 2;

// Function to illustrate traversal in arr[][]

void traverse2DArray(int arr[][M], int N)

// Iterate from [1, N-1] and print

// the element at that index

for (int i = 0; i < N; i++) {

for (int j = 0; j < M; j++) {

cout << arr[i][j] << ' ';

cout << endl;

// Driver Code

int main()

Sushma B | JSSCACS| 2024-25


C++ Programing Language 4

{ // Given array

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

// Function call

traverse2DArray(arr, N);

return 0;

OUTPUT

12

34

Strings

C++ string class internally uses character array to store character but all memory management,
allocation, and null termination are handled by string class itself that is why it is easy to use. For example
it is declared as:

char str[] = "C++STRINGS"

Below is the program to illustrate the traversal in the string:

// C++ program to illustrate the

// traversal of string

#include "iostream"

using namespace std;

// Function to illustrate traversal

// in string

void traverseString(char str[])

int i = 0;

// Iterate till we found '\0'

while (str[i] != '\0') {

Sushma B | JSSCACS| 2024-25


C++ Programing Language 5

printf("%c ", str[i]);

i++;

// Driver Code

int main()

// Given string

char str[] = "C++STRINGS";

// Function call

traverseString(str);

return 0;

Output:

C++STRINGS

The string data_type in C++ provides various functionality of string manipulation. They are:

1. strcpy(): It is used to copy characters from one string to another string.

2. strcat(): It is used to add the two given strings.

3. strlen(): It is used to find the length of the given string.

4. strcmp(): It is used to compare the two given string.

Below is the program to illustrate the above functions:

// C++ program to illustrate functions

// of string manipulation

Sushma B | JSSCACS| 2024-25


C++ Programing Language 6

#include "iostream"

#include "string.h"

using namespace std;

// Driver Code

int main()

// Given two string

char str1[100] = "HelloC++class";

char str2[100] = "HelloC++";

// To get the length of the string

// use strlen() function

int x = strlen(str1);

cout << "Length of string " << str1

<< " is " << x << endl;

cout << endl;

// To compare the two string str1

// and str2 use strcmp() function

int result = strcmp(str1, str2);

// If result is 0 then str1 and str2

// are equals

if (result == 0) {

cout << "String " << str1

<< " and String " << str2

<< " are equal." << endl;

Sushma B | JSSCACS| 2024-25


C++ Programing Language 7

else {

cout << "String " << str1

<< " and String " << str2

<< " are not equal." << endl;

cout << endl;

cout << "String str1 before: "

<< str1 << endl;

// Use strcpy() to copy character

// from one string to another

strcpy(str1, str2);

cout << "String str1 after: "

<< str1 << endl;

cout << endl;

return 0;

Output:

Length of string helloc++class is 13

String helloc++class and HelloC++ are not equal.

String str1 before: helloc++class

String str1 after: HelloC++

Sushma B | JSSCACS| 2024-25


C++ Programing Language 8

Sushma B | JSSCACS| 2024-25


C++ Programing Language 9

POINTERS
Introduction:
 Pointers are a powerful concept in C++ and have the following advantages.\
i. It is possible to write efficient programs.
ii. Memory is utilized properly.
iii. Dynamically allocate and de-allocate memory.

 Memory Utilization of Pointer:


 Memory is organized as an array of bytes. A byte is basic storage and accessible unit in memory.
 Each byte is identifiable by a unique number called address.
 We know that variables are declared before they are used in a program. Declaration of a variable
tells the compiler to perform the following.
o Allocate alocation in memory.The number of location depends on data type.
o Establish relation between address of the location and the name of the variable.
 Consider the declaration, intnum;
 This declaration tells the compiler to reserve a location in memory. We know that size of int type
is two bytes. So the location would be two bytes wide.
Address Num
100
15
101
 In the figure, num is the variable that stores the value 15 and address of num is 100. The address
of a variable is also an unsigned integer number. It can be retrieved and stored in another variable.

 Pointer:
 A pointer is a variablethat holds amemory address ofanother variable.
 The pointer has the following advantages.
o Pointers save memory space.
o Dynamically allocate and de-allocate memory.
o Easy to deal with hardware components.
o Establishes communication between program and data.
o Pointers are used for file handling.
Pointers are used to create complex data structures such as linkedlist, stacks, queues trees and
graphs.

 Pointer Declaration:

Sushma B | JSSCACS| 2024-25


C++ Programing Language 10

 Pointers are also variables and hence,they must be defined in a program like any other variable.
 The general syntax of pointer declaration is given below.
Syntax: Data_Type*Ptr_Variablename;
 Where,
o Data_Type is any valid data type supported by C++ or any user defined type.
o Ptr_Variable name is the name of the pointer variable. The presence of ‘*’ indicates that it
is a pointer variable.
 Defining pointer variables:
o int *iptr; iptr is declared to be a pointer variable of int type.
o float *fptr; fptr is declared to be a pointer variable of float type.
o char*cptr; cptr is declared to be a pointer variable of character type.

 Pointer Initialization:
 Once we declare a pointer variable, we must make it to point to something.
 We can do this by assigning or initializing to the pointer the address of the variable you want
topoint to as in: iptr = &num;
 The„&’ is the address operator and it represents address of the variable.
 Example: A program to display the content of num and the address of the variable num using a
pointer variable.

#include<iostream.h>

void main( )
{
int num; //normal integer variable
int *iptr; //Pointer declaration, pointing to integer data

num = 574; //assign value to num


iptr =&num //assign address of num to int pointer

cout<<” Value of num is :”<<num<<endl;


cout<<”Address of num is:”<<iptr<<endl;
}

 The address of operator(&):


 „&‟ is a unary operator that returns the memory address of its operand.
 For example, if var is an integer variable, then &var is its address.
We should read „&‟ operatoras“the address-of”which means & var will be read as“the address of
var”.
Ex:

Sushma B | JSSCACS| 2024-25


C++ Programing Language 11

int num=25; int *iptr;


iptr =&num; //The address of operator &
 Pointer Operatoror Indirection Operator(*):
 The second operator is indirection operator„*‟,and it is the complement of„&‟.
 It is a unary operator that returns the value of the variable located at the address specified by its
operand.
 Example:
int num = 25;
int *iptr; //Pointer Operator (Indirection Operator*)
iptr = &num;
 Example:A program executes the two operations.
#include<iostream.h>
#include<conio.h>
void main( )
{
Int num; OUTPUT:
int*iptr; Value of num is : 300
int val;
Value of pointer:0xbff64494

num = 300; Value of val : 300


iptr=&num;
val = *iptr;

cout<<”Value of num is:”<<num<<endl;


cout<<” Value of pointer :”<<iptr<<endl;
cout<<” Value of val :”<<val<<endl;
}

 Pointer Arithmetic:
 We can perform arithmetic operations on a pointer just as you can a numeric value.
 There are four arithmetic operators that can be used on pointers:
o Increment ++
o Decrement --
o Addition +
o Subtraction -
Example: iptr 1200 9
in tnum,*iptr; 1201
iptr++ 1202
Sushma B | JSSCACS| 2024-25
1203
C++ Programing Language 12

num = 9;
iptr=&num;
iptr++;
cout<<iptr;
 The following operation can be performed on pointers.
o We can add integer value to a pointer.
o We can subtract an integer value from a pointer.
o We can compare two pointers, if they point the elements of the same array.
o We can subtract one pointer from another pointer if both point to the same array.
o We can assign one pointer to another pointer provided both are of same type.
 The following operations cannot be performed on pointers.
o Addition of two pointers.
o Subtraction of one pointer from another pointer when they do not point to the same array.
o Multiplication of two pointers.
o Division of two pointers.
 A program to illustrate the pointer expression and pointer arithmetic.
#include<iostream.h>
#include<conio.h>
void main( )
{ OUTPUT:
int a, b, x,
Addressofa=65524
y;int*ptr1,*ptr2
; Addressofb=65522 a
a=30; = 30 b=6
b =6; x=30 y=6
ptr1 = &a
a=100 b =12
ptr2 =&b;
x=*ptr1 +*ptr2 – 6;
y=6-*ptr1 / *ptr2 +30;

cout<<”Addressofa=“<<ptr1<<endl;
cout<<”Addressofb=“<<ptr2<<endl;
cout<<”a = “<<a<<”b = “<<b<<endl;
cout<<”x = “<<x<<”y = “<<y<<endl;

*ptr1 =*ptr1 +70;


*ptr2 =*ptr2 * 2;
cout<<”a= “<<a<<”b= “<<b<<endl;
}

Sushma B | JSSCACS| 2024-25


C++ Programing Language 13

 Pointers and Arrays:


 There is a close relationship between array and pointers in C++.
 Consider the following program which prints the elementsof an array A.
#include<iostream.h>
voidmain( )
{

intA[5]={ 15, 25,67, 83, 12};


for(int i = 0; i<5; i++)
cout<<A[i]<<”\t”;
}

 Output of the above program is:15 25 67 83 12


 When we declare an array, its name is treated as a constant pointer to the first element of the
array.
 This is also known as the base address of the array.
 In other words base address is the address of the first element in the array of the address of a[0].
 If we use constant pointer to print array elements.
#include<iostream.h>
voidmain( )
{

intA[5]={ 15, 25,67, 83, 12};


cout<<*(A) <<”\t”;
cout<<*(A+1) <<”\t”;
cout<<*(A+2) <<”\t”;
cout<<*(A+3) <<”\t”;
cout<<*(A+4) <<”\t”;
}

 Outputof the above program is:1525


678312
 Here the expression *(A+3) has exactly same effect as A[3]in the program.
 The difference between constant pointer and the pointer variable is that the constant pointer
cannot be incremented or changed while the pointer to an array which carries the address of the
first element of the array may be incremented.
 The following example shows the relationship between pointer and one dimensional array.
#include<iostream.
h>void main( )
{

Sushma B | JSSCACS| 2024-25


C++ Programing Language 14

nt a[10],i,n;
cout<<”Entertheinputforarray”;
cin>>n;
cout<<”Enterarrayelements:”; OUTPUT:
for(i=0; i<n; i++)
cin>>*(a+i); Entertheinputforarray5 Enter
cout<<Thegivenarrayelementsare:”; for(i=0; array elements
i<n; i++)
1 2 3 4 5
cout<<”\t”<<*(a+i);g
etch( ); Thegiven arrayelementsare:
} 1 2 3 4 5
 Array of Pointers:
 There is an array of integers;array of float, similarly there can be an array of pointers.
 “An array of pointer means that it is a collection of address”.
 The general form of array of pointers declaration is:

int*pint[5];
 The above statement declares an array of 5 pointers where each of the pointer to integer variable.
 Example: Program to illustrate the array of pointers of isolatedvariables.
#include<iostream.h>
#include<conio.h>
void main( )
{
int *pint[5];
OUTPUT:
inta=10, b =20, c=30,d=40, e=50;
pint[0]=&a; Value10storedat17500
pint[1]=&b;
Value20storedat17502
pint[2]=&c;
pint[3]=&d; Value30storedat17504
pint[4]=&e; Value40storedat17506
Value50storedat17508
for(inti=0;i<=4;i++)
cout<<”Value“<<*pint[i]<<“storedat“<<pint[i]<<endl;
}

 Pointers and strings:


 String is sequence of characters ends with null(„\0‟)character.
 C++ provides two methods of declaring and initializing a string.
 Method1:

Sushma B | JSSCACS| 2024-25


C++ Programing Language 15

charstr1[ ] =“HELLO”;
 Whena string is declared using an array,the compiler reserves one element longer than the
Number of characters in the string to accommodate NULLcharacter.
 The string str1[] is 6 bytes longto initialize its first 5characters HELLO\0.
 Method2:
char*str2=“HELLO”;
 C++ treats string constants like other array and interrupts a string constant as a pointer to the first
character of the string.
 This means that we can assign a string constanto a pointer that point to a char.
 Example:A program to illustrate the difference between strings as arrays and pointers.
#include<iostream.h>
#include<conio.h>
void main( )
{
charstr1[]=“HELLO”; OUTPUT:
char *str2 = “HELLO”;
HELLO
cout<<str1<<endl;
cout<<str2<<endl; HELLO
str2++; ELLO
cout<<str2<<endl;
}

 Pointers as Function Parameters:


 A pointer can be a parameter.It works like a reference parameter to allow change to argument from
within the function.
voidswap(int*m,int *n)
{

int temp;
temp=*m;
*m = *n;
*n =temp;
}

voidswap(&num1, &num2);

 Pointers and Functions:


 A function may be invoked in one of two ways :
o Call by value
o Call by reference

Sushma B | JSSCACS| 2024-25


C++ Programing Language 16

 The second method call by reference can be used in two ways :


o By passing the references
o By passing the pointers
 Reference is an alias name for a variable.
 ForExample: int m = 23;
int&n=m; int
*p;
p =&m;
 Then the value of mi.e.23is printed in the following ways :
cout <<m; // using variable name
cout << n; //usingreferencename
cout << *p; // using the pointer

 Invoking Function by Passing the References:


 When parameters are passed to the functions by reference, then the formal parameters become
references (or aliases) to the actual parameters to the calling function.
 That means the called function does not create its own copy of original values, rather, it refers
tothe original values by different names i.e. their references.
 For example the program of swapping two variables with reference method:
#include<iostream.
h>void main()
{

voidswap(int&,int&); int
a = 5, b = 6;
cout<<“\nValueofa:”<<a<<“andb:”<<b; swap(a, b);
cout<<“\nAfter swappingvalueofa:”<< a<< “and b:” <<b;
}

voidswap(int&m,int&n)
{
OUTPUT:
int temp;
temp =m; Value of a: 5 and b : 6
m = n; After swapping value of a: 6 and b : 5
n =temp;
}

 Invoking Function by Passing the Pointers:


 When the pointers are passed to the function, the addresses of actual arguments in the calling

Sushma B | JSSCACS| 2024-25


C++ Programing Language 17

function are copied into formal arguments of the called function.


 That means using the formal arguments (the addresses of original values) in the called function; we
can make changing the actual arguments of the calling function.
 For example the program of swapping two variables with Pointers:
#include<iostream.h>
 #include<iostream.h>

void main()
{

voidswap(int*m,int*n); int
a = 5, b = 6;
cout<<“\nValueofa:”<<a<<“andb:”<<b; swap(&a, &b);
cout<<“\nAfter swappingvalueofa:”<< a<< “and b:” <<b;
}

voidswap(int *m,int *n)


{
OUTPUT:
int temp;
temp=*m; Valueofa: 5andb : 6
*m = *n;
Afterswappingvalue of a: 6 and b : 5
*n =temp;
}

 Memory Allocation of pointers:


 Memory Allocation is donein two ways:
o Static Allocation of memory
o Dynamic allocation of memory.

 Static Allocation of Memory:


 Static memory allocation refers to the process of allocating memoryduring the compilation of the
program i.e. before the program is executed.
 Example:
int a; //Allocates 2bytes of memoryspace duringthe compilation.

 Dynamic Allocation of Memory:


 Dynamic memory allocation refers to the process of allocating memory during the execution ofthe
program or at run time.
 Memory space allocated with this method is not fixed.
 C++ supports dynamic allocation and de-allocation of objects using new and delete operators.

Sushma B | JSSCACS| 2024-25


C++ Programing Language 18

 These operators allocate memory for objects from a pool called the freestore.
 The new operator calls the special function operator new and delete operators call the special
function operator delete.

 new operator:
 We can allocate storage for a variable while program is running by using new operator.
 It is used to allocate memory without having to define variables and then make pointers point to
them.

 The following code demonstrate show to allocate memory for different variables.
 To allocate memory type integer
int *pnumber;
pnumber=newint;
 The first line declares the pointer, pnumber. The second line then allocates memoryfor an integer
and then makes pnumber point to this new memory.
 To allocate memory for array, double*dptr=newdouble[25];
 To allocates dynamic structure variables orobjects, student sp =new student;

 Delete Operator:
 The delete operator is used to destroy the variables space which has been created by using the
new operator dynamically.
 Use delete operator to free dynamic memoryas : delete iptr;
 To free dynami carray memory: delete[]dptr;
 To free dynamic structure, delete structure;

 Difference between Static Memory Allocation and Dynamic Memory Allocation:

Sl no StaticMemoryAllocation DynamicMemory Allocation


Memory space is allocated before the Memory space is allocated during the
1
Execution of program. Execution of program.
2 Memory space allocated is fixed Memory space allocated is not fixed
3 More memory space is required Less memory space is required.
4 Memory allocation from stack area Memory space form heap area.

 Freestore (Heapmemory):
 Free store is a pool of memory available to allocated and de-allocated storage for the objects
during the execution of the memory.

Sushma B | JSSCACS| 2024-25


C++ Programing Language 19

 MemoryLeak:
 If the objects, that are allocated memory dynamically, are not deleted using delete, the
memoryblock remains occupied even at the end of the program.
 Such memoryblocksare known as orphaned memoryblocks.
 These orphaned memory blocks when increases in number, bring adverse effect on the system.
This situation is called memory leak.

Sushma B | JSSCACS| 2024-25

You might also like