Sunteți pe pagina 1din 58

CSEE2123: OOP and Data Structures

Fall 2018
Dynamic Memory Allocation
Type Casting
Lecture 3
M. Tahir Awan
(mtahir@cust.edu.pk)
Capital University of Science & Technology (CUST),
Islamabad
Difference between C and C++ / 1
• Below are the differences :
C C++
C is a procedural programming C++ is an object oriented
language that is based upon functions programming language that is based
upon classes and objects
In C, there is no support for function In C++ has support for function and
overloading or operator overloading operator overloading
C does not support Inheritance, C++ supports Inheritance,
Polymorphism, Virtual Functions Polymorphism and Virtual Functions

C has not so strong data abstraction/ C++ has strong data abstraction and
data security features data security features
In C variables need to be defined at In C++ Variables can be defined
start of the program anywhere in the program

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 2


Difference between C and C++ / 2
• Below are the differences :
C C++
Structures in C cannot have function Structures in C++ can have function
members members
C does not have References C++ has support for Reference
Variables, String class Variables, String class
In C, scanf and printf are used to get In C++, cin and cout is used for input
input and display output and output respectively
C does not use namespaces C++ has support for namespaces
C has no support for Exception C++ has support for exception
Handling handling
C does not support generic C++ has support for generic
programming programming through Template
Functions and Classes
9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 3
C++ : Input & Output
• Input (cin : Standard input stream)
• cin and stream extraction operator „>>‟ is used to
get input from the standard input device
(keyboard)
• Stream extraction operator : >>
• int height ;
• cin >> height;
• Waits for user to input value, press „Enter‟ key.
User input is placed in the variable „height‟
• int feet, inches No use of %d, %f, %c , &
• cin >> feet >> inches; in Cin and Cout

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 4


C++ : Input & Output
• Output (cout : standard output stream)
• cout and stream insertion operator „<<„ is used
to display output to the standard output device
(screen)
• float num = 100;
• cout << num ;
• Displays value of variable number i.e 100 on
screen
• float Temp = 98.6;
• cout << “Temperature = “<< temp << endl;
• endl causes cursor to move to beginning of next
line
9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 5
C++ : Namespaces
• A namespace is a declarative region that
provides a scope to the identifiers (functions,
variables, etc) inside it.
• Namespaces are used to organize code into
logical groups and to prevent name collisions
that can occur especially when program includes
multiple libraries
• „using namespace‟ directive :
• „using namespace‟ directive tells the compiler
that the subsequent code is making use of
names in the specified namespace
• #include <iostream>
• using namespace std;
9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 6
One-Dimensional Arrays
• An array is an indexed data structure to describe
several variables having the same data type and
name
int y[100];

y[0] y[1] y[2] … y[k-1] y[k] y[k+1] … y[98] y[99]

• An element of an array is accessed using the array


name and an index or subscript,
• In C\C++, the subscripts always start with 0
• Name of the array is the address of the first
elementCSEE2123:
9/27/2018
and the index/subscript
OOP and DS
is the offset
© M. Tahir Awan, CUST 7
2D Arrays in Memory
• 2D Arrays in C can be used to define matrices
• 2D Arrays are stored row-wise (row-major order)
in computer memory
4
int matrix[3][4];
1
0
Row 0 4 1 0 2 2D array in
memory 2
-1
Row 1 -1 2 4 3 2
4
Row 2 0 -1 3 1 3
0
-1
Column 3 3
Column 0 Column 1 Column 2
1

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 8


2-D array : Example
• Adding two matrices of size 3x3
//Adding two matrices cout<<“Sum Matrix =”;
#include <iostream>
using namespace std; for (i=0; i<3; i++){
for (j=0;j<3;j++){
void main() {
cout<<sum[i][j]<<endl;
int i,j,k;
}
int sum[3][3];
}
int m1[3][3]= {{3,4,9},
}
{12,34,40}, {11,44,31}};
int m2[3][3]= {{13,14,9},
{19,53,54}, {11,4,23}};

for (i=0; i<3; i++){


for (j=0;j<3;j++){
sum[i][j] = m1[i][j] +
m2[i][j];
}
}
9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 9
Pointer Operator
• & (address operator)
– Returns address of operand
int y = 5;
int *yPtr;
yPtr = &y; /* yPtr gets address of y */
/* OR yPtr “points to” y */

y yptr y
5 500000 600000 600000 5
yPtr

Address of y is
value of yptr

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 10


Pointer Arithmetic
• Arithmetic operations can be performed on
pointers
– Increment/decrement pointer (++ or --)
– Add an integer to a pointer( + or += , - or -=)
– Pointers may be subtracted from each other

• Pointer arithmetic is used when pointers are


used to access arrays

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 11


Pointer Arithmetic : Example
• Array names and pointers
#include <iostream>
using namespace std;

void main( void )


{
int b[5] = {10,20,30,40,50 };
int *ptr = b;

cout<<“x = “<< ptr <<endl ;


cout<<“x = “<< *ptr <<endl ;
cout<<“x = “<< *++ptr <<endl ;
cout<<“x = “<< ++*ptr <<endl ;
cout<<“x = “<< *ptr++ <<endl ;

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 12


Pointer to Pointer (**)
• C++ allows the use of pointers that point to
pointers, that ultimately points to data (or even
to other pointers)

int num = 5;
int *x;
int **y;

x = &num;
y = &x;
cout<<*x; // Print on Screen ?
cout<<**y; // Print on Screen ?
9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 13
2D Arrays : Pointer to Pointers
• 2D array elements are accessed like pointer to
pointers

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 14


2D Arrays and Pointer : Example
• 2D Array and double pointers

#include <iostream> for ( j = 0; j < 6; j++ ) {


using namespace std; cout<<" x[][] = ", *(xptr+j)
<<endl;
void main( void ) }
{
int x[2][3] = for ( i = 0; i < 2; i++ ) {
{{10,20,30},{40,50,60}}; for ( j = 0; j < 3; j++ )
int *xptr = &x[0][0]; cout << "x[][] = ",
int i,j; *(*(x+i)+j) <<endl;
}
for ( i = 0; i < 2; i++ ) { }
for ( j = 0; j < 3; j++ ) }
cout<< "x[][] = ",
x[i][j]<<endl;
}

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 15


Arrays of Pointers
• Arrays can contain pointers
• E.g: an array of strings
char *suit[ 4 ] = { "Hearts", "Diamonds",
"Clubs", "Spades" };
– Strings are pointers to the first character
– char * – each element of suit is a pointer to a char
– The strings are not actually stored in the array suit, only
pointers to the strings are stored

suit[0] ’H’ ’e’ ’a’ ’r’ ’t’ ’s’ ’\0’

suit[1] ’D’ ’i’ ’a’ ’m’ ’o’ ’n’ ’d’ ’s’ ’\0’

suit[2] ’C’ ’l’ ’u’ ’b’ ’s’ ’\0’

suit[3] ’S’ ’p’ ’a’ ’d’ ’e’ ’s’ ’\0’

– suit array has a fixed size, but strings can be of any size
9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 16
Void Pointer (Void *)
• Void pointer is a generic pointer, that can point to
objects of any data type.
• A void pointer is declared using the void keyword
and can store address of any data type
int x = 50;
float y = 5.7;
char name[30] = “Data Structures”;
void * ptr ;
ptr = &x;
ptr = &y;
ptr = name;
• To access data using void pointer, typecast it first
9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 17
Const pointer
• A const pointer is a pointer whose value can not
be changed after initialization i.e. a const pointer
will always point to the same address
int value = 50;
int *const ptr = &value;

• Const pointer to a const value


• A const pointer to a const value can not be set to
point to another address, nor can the value it is
pointing to be changed through the pointer
int value = 5;
const int *const ptr = &value;
9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 18
Dynamic memory allocation
C++ : Memory Allocation
• Two methods for memory allocation in C++
• Compile Time (or static) Allocation
• Memory for named variables/arrays is allocated
by the compiler at compile time. Exact size and
type of storage must be known. Size of array
declarations has to be constant
• Dynamic Memory Allocation
• Memory allocated "on the fly" during run time.
Dynamically allocated memory is placed in the
heap segment. Amount of memory required can
be changed at run-time.
• In C++ new and delete are used for allocation/de-
allocation of dynamic memory
9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 20
Stack vs. Heap Memory
• Stack Memory
• Stack is FILO (First In Last Out) memory
• All local variables are declared on the stack (Static
memory allocation)
• Memory is assigned/released automatically
• Memory access is Fast
• Heap Memory
• Used to store data dynamically (Size of variables
can be changed at run-time )
• Memory can be dynamically allocated/de-allocated
• Memory management is done by programmer
• Memory access is Slow
9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 21
C++ : Dynamic Memory Allocation
• Memory Allocation (new)
• To allocate space, use the operator new,
followed by the data type being allocated. For
arrays, put brackets with a size after the type
• Int * xptr = new int;
• Float * ptrArray = new float[100];
• Memory Deallocation (delete)
• To de-allocate memory, use the operator delete
• delete xptr;
• delete [] ptrArray;
• It is the programmer's job to de-allocate
dynamically created memory
9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 22
Dynamic Memory Allocation : Example
• Dynamic memory allocation of arrays.
#include <iostream> //...
using namespace std; float avg =0;
for (int i = 0; i < n; ++i) {
int main() { avg += *(ptr+i);
int n; }
cout << "Number of Students: "; avg = avg/n;
cin >> n;
float* ptr; cout << "Class Average = " <<avg
<< endl;
ptr = new float[n];
// memory released
cout << "Enter Marks." <<endl; delete [] ptr;
for (int i = 0; i < n; ++i) {
cout << "Student " << i+1 << return 0;
":"; }
cin >> *(ptr + i);
}

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 23


Practice Questions
• Write a C++ program that will ask the user to
enter a number. Program will dynamically
allocate two floating point arrays of the size
entered by the user. Program will ask the user to
enter temperature in Centigrade in one array.
Convert centigrade temperature to Fahrenheit
and store in second array. Display both the
temperatures on screen.

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 24


Array resizing using Dynamic Memory
Allocation
• Dynamic memory allocation can be used to
resize/extend existing dynamically allocated
arrays
• Procedure
–Create new array of larger size
–Copy data from old array to new array
–Delete the Old array
–Assign the pointer to the newly created
array

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 25


TypeCasting
Implicit vs. Explicit Conversion
• Implicit Conversion
• Implicit conversions are automatically performed
during program execution
• In arithmetic expressions one data type can be
converted to other data type during execution
• e.g. int x; short y = 100; x = y;

• Explicit Conversion – Typecasting


• Implicit conversions may result in error, hence
programmer can assist compiler by explicitly
telling data type of variables during execution
(Typecasting)
9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 27
C++ - Typecasting
• Type casting is a way to explicitly convert a
variable from one data type to another data type
• New data type is mentioned during assignment
of variable and in arithmetic expressions

• int x = 2500; short y; float z;

• y = (short) x; OR y = short ( x );
• z = float (x) / 33;
• z = static_cast <float> (x) / 33;
• z = reinterpret_cast <float> (x) / 33;

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 28


Typecasting : Example
• Typecasting in C++
#include <iostream> p = short ( sum );
using namespace std; result = int (da ) + int (db) +
int (dc);
void main() mean = float ( sum ) / count;
{ count = int ( ch );
int sum , count , result;
short p; cout<<"P = “<< p <<endl;
float mean, da, db, dc; cout<<"Result=“ <<result<<endl;
char ch; cout<<"Mean =“<<mean<<endl ;
cout<<"Count = “<<count<<endl;
sum = 17;count = 5;
da = 3.3 ; db = 4.5 ; dc = 9.9; }
ch = 'a';

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 29


Typecasting : Example
• Typecasting in C++ using „static_cast <type>‟
#include <iostream> result = int (da + db + dc);
using namespace std; mean = static_cast <float>(sum)
/ count;
void main() ch = reinterpret_cast <char> (p)
;
{
int sum , count , result;
cout<<"Result= " <<result<<endl;
short p;
cout<<"Mean = "<<mean<<endl ;
float mean, da, db, dc;
cout<<"ch = "<<ch<<endl;
char ch;
}

sum = 17;count = 5;
da = 3.3 ; db = 4.5 ; dc = 9.9;
ch = 'a';

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 30


C++ Typecasting : Pointers
• Typecasting can also be used with pointers
• Possible to have a float* point to an integer data
and vice versa

• int array1[100], float array2[20];


• char* ptrInt, int* ptrFloat;
• ptrInt = array1; // char ptr pointing to char array
• ptrFloat = array2; // int ptr pointing to int array
• ptrInt = reinterpret_cast <int *> arrFloat;
• ptrFloat = reinterpret_cast <float *> arrInt;

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 31


Void Pointer (Void *)
• Void pointer is a generic pointer, that can point to
objects of any data type.
• A void pointer is declared using the void keyword
and can store address of any data type
int x = 50;
float y = 5.7;
char name[30] = “Data Structures”;
void * ptr ;
ptr = &x;
ptr = &y;
ptr = name;
• To access data using void pointer, typecast it first
9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 32
C++ Typecasting : Void Pointer
• Address of any variable can be assigned to a void
pointer
• Used frequently to have a single pointer pointing
towards different memory locations carrying different
data types
• Void pointers are Useful while passing arguments to
a function

int x=10, float y = 7.25;


void *ptr;
ptr = &x;
cout << *((int*)ptr) << endl;

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 33


C++ Typecasting : Void Pointer
• Pointer Typecasting in C++
#include <iostream> ptr = &c;
using namespace std; cout << *((char*) ptr) << endl;

void main() { }

int a=10;
float b=3.95;
char c = 'A';
void* ptr;

ptr = &a;
cout << *((int*) ptr) << endl;

ptr = &b;
cout << *((float*) ptr) << endl;

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 34


Strings in C
• A string is an array of characters
– char data[10] = “Hello”;
– char data2[] = {„H‟, „e‟, „l‟, „l‟, „o‟, „\0‟}
• Print strings
– cout << data;
• String can be accessed char by char
– data[0] is first character
– Null character '\0' terminates strings
End of String
Symbol „\0‟

H e l l o \0

0 1 2 3 4 5 6 7 8 9

9/27/2018 CSEE2123: OOP and DS ©data


M. Tahir Awan, CUST 35
Strings in C++
• C++ provides following two types of string
representations:

–The C-style character string.


–The string class type introduced with
Standard C++.

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 36


C Strings : Example
• String Initialization #include <iostream>
using namespace std;
• Accessing String
elements void main( void ){
char string1[] = "Computer
Programming";
char string2[ 20 ];

cout<<"Enter your Name: ";


cin>>string2;

cout<<"String1 is: " <<string1 << "


String2 is: "<< string2 <<endl;
cout<<"String2 with spaces :\n";
int i = 0;
while ( string2[i] != '\0') {
cout<<string2[i]<<" ";
i++;
}
}
9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 37
String Class in C++
• The standard C++ library provides a string class
type that supports all the string operations
defind in library string
• Objects of type string can be defined

• String Class supports following operations :


• string text;
• text.length()  return length of string
• text.size()  return length of string
• text.find(“abc”);  find „abc‟ in string

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 38


C++ String Class : Example
//Count number of students // total lenghth of str3 after
#include <iostream> concatenation
#include <string> len = str3.size();
cout << "str3.size() : " << len
using namespace std; << endl;

int main () { return 0;


string str1 = "Hello"; }
string str2 = "World";
string str3;
int len ;

// copy str1 into str3


str3 = str1;
cout << "str3 : " << str3 <<
endl;

// concatenates str1 and str2


str3 = str1 + str2;
cout << "str1 + str2 : " << str3
<< endl;

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 39


C++ String Class : Example
• Searching a Name in the List
//Count number of students for(int i=0;i<5;i++)
#include <iostream> {
#include <string> if(Name == NameList[i])
{
using namespace std; cout<<"Name found in the
List "<<endl;
int main () { flag = 1;
}
string NameList[5] = }
{"bilal","ali","sohail","nasir","
rashid"};
if(!flag)
string Name ;
cout<<"Name not found "<<endl;
cout<<"Enter Name :";
return 0;
cin>>Name;
}
int flag = 0;

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 40


Structures & Unions
Structure in C\C++
• A structure is a collection of data values, called
data members, that form a single unit.
• Members of a structure can be of different types
• We can create new data types using structures

• Examples
struct complexNumber{
struct student{ float real;
char Name[20]; float complex;
float CGPA; };
};
struct book{
char title[30];
int price;
};
9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 42
Declaration of Structure type Variables
• Structure variables are declared like other
variables

struct student{
struct student{
char Name[20]; char Name[20];
float CGPA; float CGPA;
}; }s1, s2;
struct student s1, s2; Alternate Declaration Method
struct student *ptrs;

• Structure Members are local to the structure.


Member names are not known outside the
structure.
9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 43
Initializing Structures, Access
Structure Members
• To access a data member use
– VarName. memberName

struct Rectangle
{
float width; r1
float height;
0 width
float area;
0 height
};
r area

struct Rectangle r1;


r1.width = 4; r1.height = 5;

r1 = {4, 5, 0};
9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 44
Structures : Example
• Structure definition and usage
#include <iostream>
using namespace std; if(s1.marks >= 50)
s1.grade = 'P';
struct student { else
char name[20]; s1.grade = 'F';
int marks;
char grade; cout<<"Student Name = “<<
}; s1.name<<endl;
cout<<"Student Marks = “<<
s1.marks<<endl;
void main()
cout<<"Student Grade = “<<
{ s1.grade<<endl;
struct student s1; }

cout<<" Student Name = ";


cin>>s1.name;
cout<<" Student Marks = ";
cin>>s1.marks;

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 45


Structure and pointers
• Pointers can also be used with structures by
defining a pointer variable of type struct.

struct distance{
distance d1; float feet;
distance *ptr = &d1 float inches;
};
ptr-> feet = 10;
ptr-> inches = 5;
(*ptr).inches = 5;

• Arrow operator (->) is used with struct type


pointers to access its members.

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 46


Accessing Members of Structures
• Accessing structure members
– Dot (.) operator used with structure variables
» Syntax: structure_name.member
student s1;
cout<<s1.marks;
» Structure can also be declared and initialized as follows:
student s1;
s1.Name = “Jamal”;
s1.marks = 56;
– Arrow operator (->) used with pointers to structure variables
student s1, *ptrS;
ptrS = &s1;
cout<<ptrS->marks;
cout<<ptrS->name;
» s1->name is equivalent to (*s1).name

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 47


Structure : Memory Layout
• Elements of data structure are placed on
consecutive memory locations in memory

0-3 integer
struct calender {
int day;
4 - 12
char month[9]; 9 character
int year;
};
13 - 15 (hole)

– Quad (4 bytes) address alignment – begins 16-19 integer

(aligns) at quad address


day int 4 bytes
month char array 9 bytes
(hole) 3 bytes
year int 4 bytes

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 48


Arrays of Structures
• Arrays of structures can be declared in the same
way as array of other data types in C
• struct student{
char name[12];
int marks;
char grade;};
struct student List[20];
• List[0].marks refer to marks of first student
• List[19].grade refer to grade of last student

……….......

0 1 2 3 19
9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 49
Arrays of Structures : Example
• An array of structure is a type of array in which each
element contains a complete structure.
struct Book {
int ID;
int Pages;
float Price;
};
Book brec[100]; // declaration of array of structures

brec[100]
brec[0] brec[1] brec[99]
ID Pages Price ID Pages Price … ID Pages Price
Array of Structures : Example
• Array of Structures
#include <iostream> for(i=0;i<10;i++){
#include <string>
if(s1[i].marks >= 50)
using namespace std;
s1[i].grade = 'P';
else
struct student {
s1[i].grade = 'F';
string name;
}
int marks;
for(i=0;i<10;i++){
char grade;
cout<<"Student Name = “<<
}; s1[i].name<<endl;
void main() { cout<<"Student Marks = “<<
struct student *s1= new student s1[i].marks<<endl;
[10]; cout<<"Student Grade = “<<
int i,j; s1[i].grade<<endl;
for(i=0;i<10;i++){ }
cout<<" Student Name = "; delete [] s1;
cin>>s1[i].name; }
cout<<" Student Marks = ";
cin>>s1[i].marks;
}
9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 51
Using Structures With Functions
• Passing structures to functions
• Pass structures by Value
– Pass entire structure as function argument
– Changes made to struct members will not be
visible outside function
• Pass structures by Reference
– Pass a pointer to structure i.e. its address
– Changes made to structure members will
modify original structure
• Return Value as structure
– Function can return a structure

52
9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST
Structure Call by Reference : Example
• Structure and Pointers
#include <iostream> findGrade (ptrS);
using namespace std;
cout<<"Student Name = “<<
struct student { s1.name<<endl;
char name[20]; cout<<"Student Marks = “<<
s1.marks<<endl;
int marks;
cout<<"Student Grade = “<<
char grade; s1.grade<<endl;
}; }
void findGrade ( struct student
*ptrS);
void findGrade ( struct student
void main() { *ptrS) {
struct student s1, *ptrS; if(ptrS->marks >= 50)
ptrS = &s1; ptrS->grade = 'P';
cout<<" Student Name = "; else
cin>>s1.name; ptrS->grade = 'F„;
cout<<" Student Marks = "; }
cin>>s1.marks;

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 53


Sizeof() Operator
• The sizeof() operator returns the size of its
operand in bytes. The sizeof() operator always
precedes its operand.
sizeof(float) OR sizeof (int)
struct date{
int date;
int month;
int year;
}d1;
sizeof(d1)
• Operand may be an expression or it may be a
cast

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 54


Nested Structures
• A structure utilization within another structure is
known as nested structure. It means member of a
structure is itself structure.
struct A{
int x;
double y;
};
struct B{ record
char ch;
A var; var
}; x y
ch
Struct B record;
Nested Structures : Example
• Structures inside Structures

#include <iostream> void main()


using namespace std; {
struct Employee e1;
struct date{ e1 =
int date; {"Ali",1050,20000,{22,6,2010}};
int month;
int year; cout<<"Employee Name :“<<
e1.name<<endl;
};
cout<<"Employee ID : “<<
e1.ID<<endl;
struct Employee{ cout<<"Employee Salary : “<<
char name[20]; e1.salary<<endl;
int ID; cout<<"Employee DOJ: “<<
float salary; e1.doj.date<<“:”<<e1.doj.month<
<“:”<<e1.doj.year<<endl;
struct date doj;

}
};

9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 56


Union
• Union is a special data type in C\C++ that
enables storage of different data values in the
same memory location
• A union can contain many members, but only
one member can contain a value at any given
time
• Unions provide an efficient way of using the
same memory location for multi-purpose

union Data { union student {


int i; char Name[20];
float f; int RegNo;
char str[20]; float CGPA;
}; };
9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 57
Union : Example
• Using union in C++ #include <iostream>
#include <string>
Program using namespace std;
• Only last value union Data {
stored in union is int i;
preserved float f;
char str[20];
};
void main( ) {
union Data item;
cout<<sizeof(item)<<endl;
item.i = 10;
item.f = 310.5;
strcpy(item.str,"CUST");
cout<<"item.i: "<<item.i <<endl ;
cout<<"item.f: "<<item.f <<endl ;
cout<<"item.str: "<<item.str <<endl
;
}
9/27/2018 CSEE2123: OOP and DS © M. Tahir Awan, CUST 58

S-ar putea să vă placă și