KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming

Similar documents
C++ Programming Chapter 7 Pointers

by Pearson Education, Inc. All Rights Reserved.

COMP26120: Pointers in C (2018/19) Lucas Cordeiro

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

Lecture 05 POINTERS 1

Chapter 7. Pointers. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Pointers and Strings Prentice Hall, Inc. All rights reserved.

C++ PROGRAMMING SKILLS Part 4: Arrays

UNIT- 3 Introduction to C++

Pointers and Strings Prentice Hall, Inc. All rights reserved.

CSC 211 Intermediate Programming. Arrays & Pointers

C Pointers. 7.2 Pointer Variable Definitions and Initialization

Homework #3 CS2255 Fall 2012

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

C Pointers Pearson Education, Inc. All rights reserved.

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

C Pointers. Indirection Indirection = referencing a value through a pointer. Creating Pointers. Pointer Declarations. Pointer Declarations

Chapter 5 - Pointers and Strings

IS 0020 Program Design and Software Tools

Chapter 5 - Pointers and Strings

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

MYcsvtu Notes LECTURE 34. POINTERS

Chapter 7 Array. Array. C++, How to Program

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved.

Chapter 6 - Pointers

Fundamentals of Programming Session 20

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

What is an algorithm?

Cpt S 122 Data Structures. Introduction to C++ Part II

Functions. Introduction :

C Pointers. CS 2060 Week 6. Prof. Jonathan Ventura

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Pointers and Strings. Adhi Harmoko S, M.Komp

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

C: How to Program. Week /Apr/23

C++ Programming: From Problem Analysis to Program Design, Third Edition

UNIT-2 Introduction to C++

Arrays. Week 4. Assylbek Jumagaliyev

Introduction to Computer Science Midterm 3 Fall, Points

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Review of the C Programming Language for Principles of Operating Systems

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

CS201 Some Important Definitions

C++ for Engineers and Scientists. Third Edition. Chapter 12 Pointers

Programming for Engineers Arrays

Pointers. 10/5/07 Pointers 1

Programación de Computadores. Cesar Julio Bustacara M. Departamento de Ingeniería de Sistemas Facultad de Ingeniería Pontificia Universidad Javeriana

C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections

Chapter 7 C Pointers

Exam 3 Chapters 7 & 9

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

Pointer in C SHARDA UNIVERSITY. Presented By: Pushpendra K. Rajput Assistant Professor

Pointers in C/C++ 1 Memory Addresses 2

Outline. Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

Relationship between Pointers and Arrays

CSC 211 Intermediate Programming. Pointers

Chapter-11 POINTERS. Important 3 Marks. Introduction: Memory Utilization of Pointer: Pointer:

Object Oriented Design

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

Review of the C Programming Language


Pointers, Dynamic Data, and Reference Types

Short Notes of CS201

BITG 1113: POINTER LECTURE 12

Introduction to C Final Review Chapters 1-6 & 13

CS201 - Introduction to Programming Glossary By

Content. In this chapter, you will learn:

Functions and Recursion

Reference operator (&)

Review of Important Topics in CS1600. Functions Arrays C-strings

C Pointers. sizeof Returns size of operand in bytes For arrays: size of 1 element * number of elements if sizeof( int ) equals 4 bytes, then

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

The C++ Language. Arizona State University 1

Objectives. In this chapter, you will:

What have we learned about when we learned about function parameters? 1-1

Introduction to Scientific Computing and Problem Solving

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

C++ for Java Programmers

CS2255 HOMEWORK #1 Fall 2012

CS201- Introduction to Programming Current Quizzes

Fundamentals of Programming Session 20

Fundamentals of Programming Session 23

Operator Overloading in C++ Systems Programming

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

CS2141 Software Development using C/C++ C++ Basics

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

Programming in C++ 5. Integral data types

CHAPTER 3 Expressions, Functions, Output

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

Introduction to C++ Systems Programming

Pointers! Arizona State University 1

Transcription:

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 ARRAYS ~ VECTORS KOM3191 Object-Oriented Computer Programming

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2 What is an array? Arrays are data structures consisting of related data items of the same type. Structures and classes are each capable of holding related data items of possibly different types. Arrays, structures and classes are "static" entities in that they remain the same size throughout program execution. struct data int id_n; int age; float salary; ; int main() data employee; employee.age = 22; employee.id_n = 1; employee.salary = 12000.21;

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 3 Arrays 12 elements. the name of the array followed by the position number of an element in square brackets [ ] The position number is called a subscript or index The first element in an array has subscript 0 (zero). The highest subscript in array c is 11, which is 1 less than 12 the number of elements in the array. Array names follow the same conventions as other variable names, i.e., they must be identifiers.

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 4 Arrays A subscript must be an integer or integer expression cout << c[ 0 ] + c[ 1 ] + c[ 2 ] << endl; -45 6 0 If a program uses an expression as a subscript, then the program evaluates the expression to determine the subscript. int a=5; int b=4; c[ a + b ] = 2; c[9]=2; subscripted array name is an lvalue it can be used on the left side of an assignment, Arrays occupy space in memory. type of the elements and the number of elements required by an array: type arrayname [ arraysize ]; Then the compiler reserves the appropriate amount of memory. The arraysize must be an integer constant greater than zero.

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 5 Arrays int b[5]=0; cout<<&(b[0]) cout<<&(b[1]) cout<<&(b[2]) cout<<&(b[3]) cout<<&(b[4]) 0xbfd66580 0xbfd66584 0xbfd66588 0xbfd6658c 0xbfd66590 ( ) [ ] Parentheses, subscript ++ -- static_cast<type>() Unary postfix ++ -- + -! Unary prefix * / % Multiplicative << >> Insertion/extraction < <= > >= Relational ==!= Equality?: Conditional && Logical and Logical or = += -= *= /= %= Assignment, Comma

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 6 Array initializers int array1[ 5 ]; int i; for ( i = 0; i < 5; i++ ) array1[ i ] = 0; //or int array1[ 10 ] = 0 ; //remaining array elements are initialized to zero ---------------------------------- int array2[ 5 ] = 32, 27, 64, 18, 95; //initializer list //or int array2[]= 32, 27, 64, 18, 95; //the compiler determines the number of elements in the array using the list // int array2[ 5 ] = 32, 27, 64, 18, 95, 14 ; gives an error. for ( int i = 0; i < 5; i++ ) cout << setw( 7 ) << i << setw( 13 ) << array2[ i ] << endl; 0 32 1 27 2 64 3 18 4 95 ------------------------------------ int array3[ 5 ]=0; array3=array2; NOT OK // int *array3; array3=array2; OK

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 7 Notes on good use of arrays Referring to an element outside the array bounds is an execution-time logic error. It is not a syntax error. When looping through an array, the array subscript should never go below 0 and should always be less than the total number of elements in the array C++ Standard Library class template vector, which enables programmers to perform many operations that are not available for C++'s built-in arrays. For example, we will be able to compare vectors directly and assign one vector to another. This new array definition will enable us to input and output entire arrays with cin and cout. Const qualifier const int x; // Error: x must be initialized : a compilation error. x = 7; // Error: cannot modify a const variable : a compilation error. Const value as the array size vectors are more efficient Only constants can be used to declare the size of automatic and static arrays. Not using a constant for this purpose is a compilation error. compilation error. const int arraysize = 10; // constant variable indicating size of array 10 int a[ arraysize ] = 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 ;

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 8 Array example Top pseudo-code statement: Roll a four-sided dice 10,000 times. Track the number of occurrences of each side of a die and output these numbers First refinement Second refinement Initialize the variables Initialize array size to 4 Initialize number of rolls to 10,000 Initialize the array frequency with zeros Initialize the counter value for the rolls to zero Roll the dies a number of times, update the number of random occurrences of each side. While the counter value for the rolls is less than or equals to 10,000 roll the dice, use modulus operator with 4 update observed side s frequency Print the frequencies of the sides Initialize the side counter of the die to 1 While the side counter of the die is less than equals to the array size print frequency of the specific side of the die increment the side counter

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 9 Array example const int arraysize = 4; int frequency[ arraysize ] = 0 ; srand( time( 0 ) ); for ( int roll = 1; roll <= 10000; roll++ ) frequency[rand() % 4 ]++; cout << Side" << setw( 13 ) << "Frequency" << endl; for ( int sidecounter = 0; sidecounter < arraysize; sidecounter ++ ) cout << setw( 4 ) << sidecounter+1 << setw( 13 ) << frequency[sidecounter ] << endl;

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 10 char type arrays char string1[ ] = "first"; char string1[] = 'f', 'i', 'r', 's', 't', '\0' ; not providing a terminating null character for a string can cause logic errors. char string2[20]; cin >> string2; reads a string from the keyboard into string2 and appends the null character to the end of the string input by the user. It is the programmer's responsibility to ensure that the array into which the string is read is capable of holding any string the user types at the keyboard. By default, cin reads characters from the keyboard until the first white-space character is encountered. Thus, inputting data with cin and >> can insert data beyond the end of the array A character array representing a null-terminated string can be output with cout and <<. cout << string2 cout <<, like cin >>, does not care how large the character array is. char myarray2[5]; cin>>myarray2; // welcome cout<<myarray2; //stack smash detected./test terminated

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 11 Passing Arrays to Functions int hourlytemperatures[ 24 ]; the function call modifyarray( hourlytemperatures, 24 ); When passing an array to a function, the array size is normally passed as well, so the function can process the specific number of elements in the array. that the size of a vector is built in. every vector object "knows" its own size, which can be obtained by invoking the vector object's size member function. Thus, when we pass a vector object into a function, we will not have to pass the size of the vector as an argument vectors are more efficient

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 12 Passing Arrays to Functions Prototypes can be: void modifyarray( int [], int ); void modifyarray( int anyarrayname[], int anyvariablename ); int main() int hourlytemperatures[ 24 ]; modifyarray( hourlytemperatures, 24 ); Function definition is: void modifyarray( int b[], int sizeofarray ) for ( int k = 0; k < sizeofarray; k++ ) b[ k ] *= 2; //In main() cout<< hourlytemperatures <<endl; //In modifyarray cout<< b<<endl; 0xbf90095c 0xbf90095c indicating that modifyarray expects to receive the address of an array of integers in parameter b and the number of array elements in parameter arraysize. Because C++ passes arrays to functions by reference, when the called function uses the array name b, it will in fact be referring to the actual array in the caller

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 13 Passing Arrays to Functions Applying the const type qualifier to an array parameter in a function definition to prevent the original array from being modified in the function body is another example of the principle of least privilege. Functions should not be given the capability to modify an array unless it is absolutely necessary. void displayarray( const int b[], int sizeofarray ) for ( int k = 0; k < sizeofarray; k++ ) // b[ k ] *= 2; NOT ALLOWED cout<<b[k]<<endl; //OK

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 14 Class ~ member function example //in GradeBook.h class GradeBook public: const static int students = 10; // note public data... double getaverage(); // determine the average grade for the test... private: string coursename; int grades[ students ]; ; There are variables for which each object of a class does not have a separate copy. That is the case with static data members, which are also known as class variables. When objects of a class containing static data members are created, all the objects of that class share one copy of the class's static data members. A static data member can be accessed within the class definition and the memberfunction definitions just like any other data member. A public static data member can also be accessed outside of the class, even when no objects of the class exist, using the class name followed by the binary scope resolution operator (::) and the name of the data member.

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 15 Class ~ member function example //in GradeBook.cpp double GradeBook::getAverage() int total = 0; double average; for ( int grade = 0; grade < students; grade++ ) total += grades[ grade ]; average=static_cast <double >( total ) / students; cout<<average; return average; //in main() int gradesarray[ GradeBook::students ] = 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 ; GradeBook mygradebook Kom3191 OOP, gradesarray; mygradebook.getaverage(); //84.9

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 16 Insertion sort, selection sort Insertion sort Example: The following table shows the steps for sorting the sequence 3, 7, 4, 9, 5, 2, 6, 1. In each step, the item under consideration is underlined. The item that was moved (or left in place because it was biggest yet considered) in the previous step is shown in bold. 3 7 4 9 5 2 6 1 3 7 4 9 5 2 6 1 3 7 4 9 5 2 6 1 3 4 7 9 5 2 6 1 3 4 7 9 5 2 6 1 3 4 5 7 9 2 6 1 2 3 4 5 7 9 6 1 // find the exact location (amongst the previous ones) of 6 and insert it there 2 3 4 5 6 7 9 1 1 2 3 4 5 6 7 9 selection sort Here is an example of this sort algorithm sorting five elements: 64 25 12 22 11 find the smallest of 64 25 12 22 11 and place as the 1 st number 11 25 12 22 64 find the smallest of 25 12 22 64 and place as 2 nd number 11 12 25 22 64 11 12 22 25 64 11 12 22 25 64 http://en.wikipedia.org/wiki

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 17 Bubble sort First Pass: ( 5 1 4 2 8 ) ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1. ( 1 5 4 2 8 ) ( 1 4 5 2 8 ), Swap since 5 > 4 ( 1 4 5 2 8 ) ( 1 4 2 5 8 ), Swap since 5 > 2 ( 1 4 2 5 8 ) ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them. Second Pass: ( 1 4 2 5 8 ) ( 1 4 2 5 8 ) ( 1 4 2 5 8 ) ( 1 2 4 5 8 ), Swap since 4 > 2 ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted. Third Pass: ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) http://en.wikipedia.org/wiki

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 18 Multidimensional arrays By convention, the first identifies the element's row and the second identifies the element's column. Arrays that require two subscripts to identify a particular element are called two-dimensional arrays or 2-D arrays. Note that multidimensional arrays can have more than two dimensions a[ i ][ j ] s

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 19 Multidimensional arrays int b[ 2 ][ 2 ] = 1, 3, 4 initializes b[ 0 ][ 0 ] to 1, b[ 0 ][ 1 ] to 0, b[ 1 ][ 0 ] to 3 and b[ 1 ][ 1 ] to 4 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 ; array1 array2 array3 1 2 3 4 5 6 1 2 3 4 5 0 1 2 0 4 0 0 for ( column = 0; column < 4; column++ ) a[ 2 ][ column ] = 0; total = 0; for ( row = 0; row < 3; row++ ) for ( column = 0; column < 4; column++ ) total += a[ row ][ column ];

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 20 C++ Standard Library Class Template vector #include <vector> void inputvector( vector< int >& array ) for ( size_t i = 0; i < array.size(); i++ ) cin >> array[ i ]; int main() vector< int > integers1( 10 ); vector< int > integers2( 10 ); cout<<integers1.size(); if ( integers1!= integers2 ) cout << "integers1 and integers2 are not equal" << endl; vector< int > integers3( integers1 ); // copy constructor integers1 = integers2; cout << "\nintegers1[5] is " << integers1[ 5 ]; integers1.at( 15 ) = 1000; // ERROR: out of range

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 21 POINTERS KOM3191 Object-Oriented Computer Programming

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 22 Pointers Pointer variables contain memory addresses as their values. aptr has the address information of the variable int *aptr; // declares the variable aptr to be type of int // it is a pointer to an int variable-value // an asterisk * must precede the pointer variable // in the declaration * is not an operator aptr addr_a addr_aptr addr_a 5 a int a=5; aptr=&a; //address operator (&) is a unary operator //it returns the memory address of its operand. //use of the & in a reference variable declaration was different Normally, a variable directly contains a specific value. However, a pointer contains the memory address of a variable that, in turn, contains a specific value. A pointer indirectly references a value Referencing a value through a pointer is often called indirection.

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 23 Pointers cout << *aptr << endl; *aptr=7; // The dereferenced pointer is an lvalue. cin >> *aptr; * here is indirection or dereferencing operator Dereferencing a pointer that has not been properly initialized could cause a fatal execution-time error An attempt to dereference a variable that is not a pointer is a compilation error. The address of a is : &a = The value of aptr = aptr; The value of a = *aptr The information &*aptr =*&aptr = aptr

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 24 Pointers ( ) [ ] Parentheses, subscript ++ -- static_cast<type>() Unary postfix ++ -- + -! & * Unary prefix * / % Multiplicative << >> Insertion/extraction < <= > >= Relational ==!= Equality?: Conditional && Logical and Logical or = += -= *= /= %= Assignment, Comma

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 25 Passing arguments to functions pass-by-value return can be used to return one value from a called function to a caller pass-by-reference arguments can be passed to a function using reference arguments Reference arguments also enable programs to pass large data objects to a function and avoid the overhead of passing the objects by value pass-by-value int incrementbyref (int num) num++; return num; pass-by-reference with a pointer argument void incrementbyref2 (int *numptr) (*numptr)++; pass-by-reference with a reference argument void incrementbyref1 (int &num) num++; numptr is a pointer to an int num is a reference to an int

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 26 Passing arguments to functions In C++, programmers can use pointers and the indirection operator (*) to accomplish pass-by-reference When calling a function with an argument that should be modified, the address of the argument is needed. This can be normally accomplished by applying the address operator (&) to the name of the variable whose value will be modified. Arrays are not passed using operator &, because the name of the array is the starting location in memory of the array (i.e., an array name is already a pointer). The name of an array, arrayname, is equivalent to &arrayname[ 0 ]. When the address of a variable is passed to a function, the indirection operator (*) can be used in the function to form a synonym for the name of the variable this in turn can be used to modify the value of the variable at that location in the caller's memory.

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 27 Passing arguments to function by-reference with pointers int main() int a=5; int *aptr=&a; cout<<incrementbyvalue(a)<<endl; //6 cout<<a<<endl; // a is 5 incrementbyref1(a); cout<<a<<endl; // a is 6 incrementbyref2(aptr); cout<<a<<endl; // a is 7 incrementbyref2(&a); cout<<a<<endl; // a is 8 return 0; A function receiving an address as an argument must define a pointer parameter to receive the address int incrementbyvalue(int b) return ++b; void incrementbyref1(int &b) b++; void incrementbyref2(int* bptr) (*bptr)++;

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 28 Passing arguments to function by-reference with pointers In the function header and in the prototype for a function that expects a onedimensional array as an argument, the pointer notation may be used. The compiler does not differentiate between a function that receives a pointer and a function that receives a one-dimensional array. When the compiler encounters the form int b[], the compiler converts the parameter to the pointer notation int *b (pronounced "b is a pointer to an integer"). void modifyarray( int [], int ); // or void modifyarray( int *, int ); int main() int hourlytemperatures[ 24 ]; modifyarray( hourlytemperatures, 24 ); Function definition is: void modifyarray( int b[], int sizeofarray ) // or void modifyarray( int *b, int sizeofarray ) for ( int k = 0; k < sizeofarray; k++ ) b[ k ] *= 2;

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 29 Using const with Pointers In pass-by-value a copy of the argument (or arguments) in the function call is made and passed to the function. If the copy is modified in the function, the original value is maintained in the caller without change In pass-by-reference the value of the passed argument is modified so the function can accomplish its task. However, in some instances, the value should not be altered in the called function, called function should manipulate only a copy of the original value. void printcharacters( const char *sptr ) for ( ; *sptr!= '\0'; sptr++ ) cout << *sptr; void copyarray( const int *src, int *dest, int SIZE ) for ( int k = 0; k < sizeofarray; k++ ) dest[k] =src[k]; //src[k]=0; // NOT ALLOWED : // error: cannot modify a const object

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 30 (non)constant pointer to (non)constant data int x, y; int * const ptr=&x; *ptr=7; ptr=&y; // not allowed ptr is const ----- int x=5, y; const int * const ptr=&x; *ptr=7; // not allowed *ptr is const ptr=&y; // not allowed ptr is const The const qualifier enables the programmer to inform the compiler that the value of a particular variable should not be modified. int * ptr - pointer to int const int * ptr - pointer to const int int * const ptr - const pointer to int const int * const ptr - const pointer to const int

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 31 sizeof operator int array[ 20 ]; int *ptr = array; cout << "\nsizeof array = " << sizeof(array); cout << "\nsizeof ptr = " << sizeof(ptr); sizeof array = 80 sizeof ptr = 4 C++ provides the unary operator sizeof to determine the size of an array (or of any other data type, variable or constant) in bytes When applied to the name of an array the sizeof operator returns the total number of bytes in the array as a value of type size_t (an alias for unsigned int on most compilers). the sizeof operator returns the size of the pointer in bytes (4), not the size of the array. sizeof(array)/sizeof(int) = 20 When writing programs that depend on data type sizes, and that will run on several computer systems, use sizeof to determine the number of bytes used to store the data types.

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 32 sizeof operator int a[3]=0; print(a); cout<<sizeof(a)<<endl; // 12... void print(int a[]) cout<<sizeof(a)<<endl; // 4?? cout<<"ptr : "<<ptr<<endl; Because sizeof is a compile-time unary operator, not an run-time operator, using sizeof does not negatively impact execution performance. sizeof() gives you the size of the data type, not the size of a particular instance of that type in memory. For example, if you had a string data object that allocated a variable size character array at runtime, sizeof() could not be used to determine the size of that character array. It would only give you the size of the pointer string mystring; cin>>mystring; cout<<sizeof(mystring)<<endl; //4??

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 33 Pointer arithmetic int v[5]=0; int *vptr = v; // or int *vptr = &v[ 0 ]; vptr += 2; // -- ++ -= += allowed Pointers are valid operands in arithmetic expressions, assignment expressions and comparison expressions vptr has been initialized to point to v[ 0 ] In conventional arithmetic, the addition 3000 + 2 yields the value 3002. This is normally not the case with pointer arithmetic. 3008 (3000 + 2 * 4) Pointer arithmetic is meaningless unless performed on a pointer that points to an array Subtracting or comparing two pointers that do not refer to elements of the same array is a logic error Using pointer arithmetic to increment or decrement a pointer such that the pointer refers to an element past the end of the array or before the beginning of the array is normally a logic error. Pointers can be compared using equality and relational operators. Comparisons using relational operators are meaningless unless the pointers point to members of the same array.

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 34 Pointer vs array int b[ 5 ]; // create 5-element int array b int *bptr; // create int pointer bptr Because the array name (without a subscript) is a (constant) pointer to the first element of the array, we can set bptr to the address of the first element in array b with the statement bptr = b; // assign address of array b to bptr This is equivalent to taking the address of the first element of the array as follows: bptr = &b[ 0 ]; // also assigns address of array b to bptr Array element b[ 3 ] can alternatively be referenced with the pointer expression *( bptr + 3 )

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 35 Pointer vs array The array name can be treated as a pointer and used in pointer arithmetic. For example, the expression *( b + 3 ) is b[ 3 ]. In general, all subscripted array expressions can be written with a pointer and an offset For example, the expression bptr[ 1 ] refers to the array element b[ 1 ]; this expression uses pointer/subscript notation. Remember that an array name is a constant pointer; it always points to the beginning of the array. Thus, the expression b += 3 // NOT ALLOWED array names are pointers to the beginning of the array and pointers can be modified in arithmetic expressions, array names cannot be modified in arithmetic expressions, because array names are constant pointers.

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 36 Array of pointers Arrays may contain pointers. A common use of such a data structure is to form an array of pointer-based strings, referred to simply as a string array. Each entry in the array is a string, but in C++ a string is essentially a pointer to its first character, so each entry in an array of strings is simply a pointer to the first character of a string. const char *days[ 4 ] = monday", tuesday", wednesday", thursday" ; The const char * portion of the declaration indicates that each element of array suit is of type "pointer tochar constant data Each is stored in memory as a null-terminated character string that is one character longer than the number of characters between quotes. The strings could be placed into a two-dimensional array, in which each row represents one suit and each column represents one of the letters of a suit name. Such a data structure must have a fixed number of columns per row, and that number must be as large as the largest string.

KOM3191 Object Oriented Programming Dr Muharrem Mercimek 37 void pointers The void pointer can be point at objects of any data type! A void pointer is declared like a normal pointer, using the void keyword as the pointer s type: void *ptrvoid; // ptrvoid is a void pointer However, because the void pointer does not know what type of object it is pointing to, it can not be dereferenced! Rather, the void pointer must first be explicitly cast to another pointer type before it is dereferenced. they effectively allow you to avoid type checking int nvalue = 5; void *pvoid = &nvalue; // can not dereference pvoid because it is a void pointer int *pint = static_cast<int*>(pvoid); // cast from void* to int* cout << *pint << endl; // can dereference pint