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

Size: px
Start display at page:

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

Transcription

1 Pointers and Strings 1 Introduction Pointer Variable Declarations and Initialization Pointer Operators Calling Functions by Reference Using const with Pointers Selection Sort Using Pass-by-Reference

2 2 Introduction Pointers Powerful, but difficult to master Enable pass-by-reference and allow the creation of dynamic data structure (e.g., linked lists, queues, etc.) Close relationship with arrays and strings

3 Pointer Variable Declarations and Initialization 3 Pointer variables Contain memory addresses as values Normally, variable contains specific value (direct reference) Pointers contain address of a variable that itself has specific value (indirect reference) Indirection Referencing value through pointer Pointer declarations * indicates variable is pointer int *myptr; declares pointer to int, pointer of type int * Multiple pointers require multiple asterisks int *myptr1, *myptr2; countptr count 7 count 7

4 Pointer Variable Declarations and Initialization 4 Can declare pointers to any data type Pointer initialization Initialized to 0, NULL, or address 0 or NULL points to nothing (null pointer) NULL defined in <iostream>

5 5 Pointer Operators & (address operator) Returns memory address of its operand Example int y = 5; int *yptr; yptr = &y; yptr points to y // yptr gets address of y yptr y 5 yptr y address of y is value of yptr

6 6 Pointer Operators * (indirection or dereferencing operator) Returns synonym for the object its pointer operand points to. *yptr returns y (because yptr points to y ) Example: cout << *yptr << endl; returns the value of y cout << y << endl; dereferenced pointer is lvalue *yptr = 9; // assigns 9 to y cin >> *yptr; // receive a value from input * and & are inverses of each other

7 1 // Fig. 8.4: fig08_04.cpp 2 // Using the & and * operators. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 int main() 9 { 10 int a; // a is an integer 11 int *aptr; // aptr is a pointer to an integer a = 7; 14 aptr = &a; // aptr assigned address of a cout << "The address of a is " << &a 17 << "\nthe value of aptr is " << aptr; cout << "\n\nthe value of a is " << a 20 << "\nthe value of *aptr is " << *aptr; cout << "\n\nshowing that * and & are inverses of " 23 << "each other.\n&*aptr = " << &*aptr 24 << "\n*&aptr = " << *&aptr << endl; 25 * and & are inverses of each other 7

8 26 return 0; // indicates successful termination } // end main 8 The address of a is 0012FED4 The value of aptr is 0012FED4 The value of a is 7 The value of *aptr is 7 Showing that * and & are inverses of each other. &*aptr = 0012FED4 *&aptr = 0012FED4 * and & are inverses; same result when both applied to aptr

9 9 Calling Functions by Reference 3 ways to pass arguments to function Pass-by-value Pass-by-reference with reference arguments Pass-by-reference with pointer arguments return can return one value from function Arguments passed to function using reference arguments Modify original values of arguments Eliminate the overhead of passing large objects! More than one value returned

10 10 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 (pointer to the first element in the array, &arrayname[0]) * operator is used in the function as alias/nickname for variable A function receiving an address as an argument must define a pointer parameter to receive the address

11 1 // Fig. 8.6: fig08_06.cpp 2 // Cube a variable using pass-by-value. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 int cubebyvalue( int ); // prototype 9 10 int main() 11 { 12 int number = 5; cout << "The original value of number is " << number; // pass number by value to cubebyvalue 17 number = cubebyvalue( number ); 18 Pass number by value; result returned by cubebyvalue 19 cout << "\nthe new value of number is " << number << endl; return 0; // indicates successful termination } // end main 24 11

12 25 // calculate and return cube of integer argument 26 int cubebyvalue( int n ) 27 { 28 return n * n * n; // cube local variable cubebyvalue n and return receives result 29 parameter passed-by-value 30 } // end function cubebyvalue The original value of number is 5 The new value of number is 125 Cubes and returns local variable n 12

13 1 // Fig. 8.7: fig08_07.cpp 2 // Cube a variable using pass-by-reference 3 // with a pointer argument. 4 #include <iostream> 5 6 using std::cout; 7 using std::endl; 8 9 void cubebyreference( int * ); // prototype int main() 12 { 13 int number = 5; 14 Prototype indicates parameter is pointer to int 15 cout << "The original value of number is " << number; 16 Apply address operator & to pass address of number to cubebyreference 17 // pass address of number to cubebyreference 18 cubebyreference( &number ); cout << "\nthe new value of number is " << number << endl; return 0; // indicates successful termination } // end main 25 cubebyreference modified variable number 13

14 26 // calculate cube of *nptr; modifies variable number in main 27 void cubebyreference( int *nptr ) 28 { 29 *nptr = *nptr * *nptr * *nptr; // cube *nptr } // end function cubebyreference The original value of number is 5 The new value of number is 125 cubebyreference receives address of int variable, i.e., pointer to an int Modify and access int variable using indirection operator * 14

15 Using const with Pointers 15 const qualifier Value of variable should not be modified const used when function does not need to change a variable Principle of least privilege Award a function enough access to accomplish its task, but no more Four ways to pass pointer to function Non-constant pointer to non-constant data Highest amount of access is granted Non-constant pointer to constant data Constant pointer to non-constant data Constant pointer to constant data Least amount of access is granted

16 1 // Fig. 8.10: fig08_10.cpp 2 // Converting lowercase letters to uppercase letters 3 // using a non-constant pointer to non-constant data. 4 #include <iostream> 5 6 using std::cout; 7 using std::endl; 8 9 #include <cctype> // prototypes for islower and toupper void converttouppercase( char * ); int main() Parameter is non-constant pointer to non-constant data 14 { 15 char phrase[] = "characters and $32.98"; cout << "The phrase before conversion is: " << phrase; 18 converttouppercase( phrase ); 19 cout << "\nthe phrase after conversion is: " 20 << phrase << endl; return 0; // indicates successful termination } // end main 25 converttouppercase modifies variable phrase 16

17 26 // convert string to uppercase letters 27 void converttouppercase( char *sptr ) 28 { 29 while ( *sptr!= '\0' ) { // current character is not '\0' if ( islower( *sptr ) ) // if character is lowercase, 32 *sptr = toupper( *sptr ); // convert to uppercase sptr; // move sptr to next character in string } // end while } // end function converttouppercase 17 The phrase before conversion is: characters and $32.98 The phrase after conversion is: CHARACTERS AND $32.98

18 1 // Fig. 8.11: fig08_11.cpp 2 // Printing a string one character at a time using 3 // a non-constant pointer to constant data. 4 #include <iostream> 5 6 using std::cout; 7 using std::endl; 8 9 void printcharacters( const char * ); int main() 12 { 13 const char phrase[] = "print characters of a string"; cout << "The string is:\n"; 16 printcharacters( phrase ); 17 cout << endl; return 0; // indicates successful termination } // end main 22 Parameter is non-constant pointer to constant data. Pass pointer phrase to function printcharacters. 18 a non-constant pointer to constant data is a pointer that can be modified to point to any data item of the appropriate type, but the data to which it points cannot be modified through that pointer

19 23 // sptr cannot modify the character to which it points, 24 // i.e., sptr is a "read-only" pointer 25 void printcharacters( const char *sptr ) 26 { 27 for ( ; *sptr!= '\0'; sptr++ ) // no initialization 28 cout << *sptr; } // end function printcharacters The string is: print characters of a string sptr is non-constant pointer to constant data; cannot modify character to which sptr points. Increment sptr to point to next character. 19

20 1 // Fig. 8.12: fig08_12.cpp 2 // Attempting to modify data through a 3 // non-constant pointer to constant data. 4 5 void f( const int * ); // prototype 6 7 int main() 8 { 9 int y; f( &y ); // f attempts illegal modification return 0; // indicates successful termination } // end main // xptr cannot modify the value of the variable 18 // to which it points 19 void f( const int *xptr ) 20 { 21 *xptr = 100; // error: cannot modify a const object } // end function f Parameter is non-constant pointer to constant data. Pass address of int variable y to attempt illegal modification. Attempt to modify const object pointed to by xptr. d:\cpphtp8_examples\ch08\fig08_12.cpp(21) : error C2166: l-value specifies const object Error produced when attempting to compile. 20

21 21 Using const with Pointers const pointers Always point to same memory location Default for array name Must be initialized when declared

22 1 // Fig. 8.13: fig08_13.cpp 2 // Attempting to modify a constant pointer to 3 // non-constant data. 4 5 int main() 6 { 7 int x, y; 8 9 // ptr is a constant pointer to an integer that can 10 // be modified through ptr, but ptr always points to the 11 // same memory location. 12 int * const ptr = &x; *ptr = 7; // allowed: *ptr is not const 15 ptr = &y; // error: ptr is const; cannot assign new address return 0; // indicates successful termination } // end main 22 d:\cpphtp8_examples\ch08\fig08_13.cpp(15) : error C2166: l-value specifies const object a constant pointer to non-constant data is a pointer that always points to the same memory location. Data at that location can be changed through the pointer. (e.g., array name)

23 1 // Fig. 8.14: fig08_14.cpp 2 // Attempting to modify a constant pointer to constant data. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 int main() 9 { 10 int x = 5, y; // ptr is a constant pointer to a constant integer. 13 // ptr always points to the same location; the integer 14 // at that location cannot be modified. 15 const int * const ptr = &x; cout << *ptr << endl; *ptr = 7; // error: *ptr is const; cannot assign new value 20 ptr = &y; // error: ptr is const; cannot assign new address return 0; // indicates successful termination } // end main a constant pointer to a constant data is a pointer that always points to the same memory location and data at that location cannot be modified. 23

24 d:\cpphtp8_examples\ch08\fig08_14.cpp(19) : error C2166: l-value specifies const object d:\cpphtp8_examples\ch08\fig08_14.cpp(20) : error C2166: l-value specifies const object Line 19 generates compiler error by attempting to modify Line constant 20 generates object. compiler error by attempting to assign new address to constant pointer. 24

25 25 Selection Sort Using Pass-by-Reference Implement selectionsort using pointers Want function swap to access array elements Individual array elements: scalars Passed by value by default Pass by reference using address operator & Selection sort: First iteration: select smallest element in array and swap it with first element of array Second iteration: select second smallest and swap it with second element in array Etc..

26 1 // Fig. 8.15: fig08_15.cpp 2 // This program puts values into an array, sorts the values into 3 // ascending order, and prints the resulting array. 4 #include <iostream> 5 6 using std::cout; 7 using std::endl; 8 9 #include <iomanip> using std::setw; void selectionsort( int *, const int ); // prototype 14 void swap( int * const, int * const ); // prototype int main() 17 { 18 const int arraysize = 10; 19 int a[ arraysize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; cout << "Data items in original order\n"; for ( int i = 0; i < arraysize; i++ ) 24 cout << setw( 4 ) << a[ i ]; 25 26

27 26 selectionsort( a, arraysize ); // sort the array cout << "\ndata items in ascending order\n"; for ( int j = 0; j < arraysize; j++ ) 31 cout << setw( 4 ) << a[ j ]; cout << endl; return 0; // indicates successful termination } // end main // sort an array of integers using selection sort algorithm 40 void selectionsort( int *array, const int size ) 41 { 42 int smallest; 43 for ( int i = 0; i < size - 1; i++ ) // loop over size-1 elements 44 { 45 smallest = i; 46 for ( int index = i + 1; index < size; index++ ) 47 if ( array[ index ] < array[ smallest ] ) 48 smallest = index; 49 // swap adjacent elements if they are out of order 50 swap( &array[ i ], &array[ smallest ] ); 51 } // end for 52 } // end function selectionsort 27

28 53 54 // swap values at memory locations to which 55 // element1ptr and element2ptr point 56 void swap( int * const element1ptr, int * const element2ptr ) 57 { 58 int hold = *element1ptr; 59 *element1ptr = *element2ptr; 60 *element2ptr = hold; } // end function swap Pass arguments by reference, allowing function to swap values at memory locations. 28 Data items in original order Data items in ascending order

Pointers and Strings. Adhi Harmoko S, M.Komp

Pointers and Strings. Adhi Harmoko S, M.Komp Pointers and Strings Adhi Harmoko S, M.Komp Introduction Pointers Powerful, but difficult to master Simulate call-by-reference Close relationship with arrays and strings Pointer Variable Declarations and

More information

C Pointers. 7.2 Pointer Variable Definitions and Initialization

C Pointers. 7.2 Pointer Variable Definitions and Initialization 1 7 C Pointers 7.2 Pointer Variable Definitions and Initialization Pointer variables Contain memory addresses as their values Normal variables contain a specific value (direct reference) Pointers contain

More information

Chapter 5 - Pointers and Strings

Chapter 5 - Pointers and Strings Chapter 5 - Pointers and Strings 1 5.1 Introduction 5.2 Pointer Variable Declarations and Initialization 5.3 Pointer Operators 5.4 Calling Functions by Reference 5.5 Using const with Pointers 5.6 Bubble

More information

Chapter 5 - Pointers and Strings

Chapter 5 - Pointers and Strings Chapter 5 - Pointers and Strings 1 5.1 Introduction 2 5.1 Introduction 5.2 Pointer Variable Declarations and Initialization 5.3 Pointer Operators 5. Calling Functions by Reference 5.5 Using const with

More information

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

Chapter 7. Pointers. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 7 Pointers Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 2 Chapter 7 - Pointers 7.1 Introduction 7.2 Pointer Variable Definitions and Initialization

More information

Outline. Introduction. Pointer variables. Pointer operators. Calling functions by reference. Using const with pointers. Examples.

Outline. Introduction. Pointer variables. Pointer operators. Calling functions by reference. Using const with pointers. Examples. Outline Introduction. Pointer variables. Pointer operators. Calling functions by reference. Using const with pointers. Examples. 1 Introduction A pointer is a variable that contains a memory address Pointers

More information

Pointers. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Pointers. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Pointers Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline 7.1 Introduction 7.2 Pointer Variable Definitions and Initialization 7.3 Pointer

More information

C Pointers Pearson Education, Inc. All rights reserved.

C Pointers Pearson Education, Inc. All rights reserved. 1 7 C Pointers 2 Addresses are given to us to conceal our whereabouts. Saki (H. H. Munro) By indirection find direction out. William Shakespeare Many things, having full reference To one consent, may work

More information

Chapter 6 - Pointers

Chapter 6 - Pointers Chapter 6 - Pointers Outline 1 Introduction 2 Pointer Variable Declarations and Initialization 3 Pointer Operators 4 Calling Functions by Reference 5 Using the const Qualifier with Pointers 6 Bubble Sort

More information

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

C Pointers. Indirection Indirection = referencing a value through a pointer. Creating Pointers. Pointer Declarations. Pointer Declarations 55:017, Computers in Engineering C Pointers C Pointers Powerful C feature but challenging to understand Some uses of pointers include Call by reference parameter passage Dynamic data structures Data structures

More information

Lecture 05 POINTERS 1

Lecture 05 POINTERS 1 Lecture 05 POINTERS 1 Pointers Powerful, but difficult to master Simulate call-by-reference Close relationship with arrays and strings Pointer Variable vs. Normal Variable Normal variables contain a specific

More information

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

Outline. Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary Pointers 1 2 Outline Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary 3 Computer Memory Revisited Computers store data in memory slots Each slot has an

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 Program Components in C++ 2 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 2 Functions and Arrays Jan 13, 200 Modules: functionsand classes Programs use new and prepackaged

More information

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

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 1 ARRAYS Arrays 2 Arrays Structures of related data items Static entity (same size

More information

POINTERS. Content. Pointers. Benefits of Pointers. In this chapter, you will learn:

POINTERS. Content. Pointers. Benefits of Pointers. In this chapter, you will learn: Content POINTERS Erkut ERDEM Hacettepe University December 2010 In this chapter, you will learn: To be able to use pointers. To be able to use pointers to pass arguments to functions using call by reference.

More information

C++ Programming Chapter 7 Pointers

C++ Programming Chapter 7 Pointers C++ Programming Chapter 7 Pointers Yih-Peng Chiou Room 617, BL Building (02) 3366-3603 ypchiou@cc.ee.ntu.edu.tw Photonic Modeling and Design Lab. Graduate Institute of Photonics and Optoelectronics & Department

More information

Pointers in C. Recap: Anatomy of a Typical C Program. declarations variables functions. int main (void){ declarations; statements; return value; }

Pointers in C. Recap: Anatomy of a Typical C Program. declarations variables functions. int main (void){ declarations; statements; return value; } Recap: Anatomy of a Typical C Program #preprocessor directives Pointers in C BBM 101 - Introduction to Programming I Hacettepe University Fall 2016 Fuat Akal, Aykut Erdem, Erkut Erdem declarations variables

More information

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples. Outline Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples. 1 Arrays I Array One type of data structures. Consecutive group of memory locations

More information

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

COMP26120: Pointers in C (2018/19) Lucas Cordeiro COMP26120: Pointers in C (2018/19) Lucas Cordeiro lucas.cordeiro@manchester.ac.uk Organisation Lucas Cordeiro (Senior Lecturer, FM Group) lucas.cordeiro@manchester.ac.uk Office: 2.44 Office hours: 10-11

More information

Arrays. Week 4. Assylbek Jumagaliyev

Arrays. Week 4. Assylbek Jumagaliyev Arrays Week 4 Assylbek Jumagaliyev a.jumagaliyev@iitu.kz Introduction Arrays Structures of related data items Static entity (same size throughout program) A few types Pointer-based arrays (C-like) Arrays

More information

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

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types Chapter 4 - Arrays 1 4.1 Introduction 4.2 Arrays 4.3 Declaring Arrays 4.4 Examples Using Arrays 4.5 Passing Arrays to Functions 4.6 Sorting Arrays 4.7 Case Study: Computing Mean, Median and Mode Using

More information

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

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) Chapter - Arrays 1.1 Introduction 2.1 Introduction.2 Arrays.3 Declaring Arrays. Examples Using Arrays.5 Passing Arrays to Functions.6 Sorting Arrays. Case Study: Computing Mean, Median and Mode Using Arrays.8

More information

Fundamentals of Programming Session 19

Fundamentals of Programming Session 19 Fundamentals of Programming Session 19 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips Lab6 Array I Objectivities 1. Using rand to generate random numbers and using srand to seed the random-number generator. 2. Declaring, initializing and referencing arrays. 3. The follow-up questions and

More information

Operating Systems 2INC0 C course Pointer Advanced. Dr. Ir. Ion Barosan

Operating Systems 2INC0 C course Pointer Advanced. Dr. Ir. Ion Barosan Operating Systems 2INC0 C course Pointer Advanced Dr. Ir. Ion Barosan (i.barosan@tue.nl) Containt Pointers Definition and Initilization Ponter Operators Pointer Arithmetic and Array Calling Functions by

More information

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

C Pointers. CS 2060 Week 6. Prof. Jonathan Ventura CS 2060 Week 6 1 Pointer Variables 2 Pass-by-reference 3 const pointers 4 Pointer arithmetic 5 sizeof 6 Arrays of pointers 7 Next Time Pointers The pointer is one of C s most powerful and important features.

More information

Chapter 15 - C++ As A "Better C"

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

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

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming 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

More information

Chapter 7 C Pointers

Chapter 7 C Pointers Chapter 7 C Pointers Objectives of This Chapter Definition and Operations with Pointers Using Pointers to pass arguments as call by reference call. Using Pointers to deal with arrays and strings. Character

More information

C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

C++ As A Better C Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan. C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2013 Fall Outline 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.5

More information

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

Pointers and Strings Prentice Hall, Inc. All rights reserved. Pointers and Strings 1 sizeof operator Pointer Expressions and Pointer Arithmetic Relationship Between Pointers and Arrays Arrays of Pointers Case Study: Card Shuffling and Dealing Simulation sizeof operator

More information

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

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty! Chapter 6 - Functions return type void or a valid data type ( int, double, char, etc) name parameter list void or a list of parameters separated by commas body return keyword required if function returns

More information

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad CHAPTER 3 ARRAYS Dr. Shady Yehia Elmashad Outline 1. Introduction 2. Arrays 3. Declaring Arrays 4. Examples Using Arrays 5. Multidimensional Arrays 6. Multidimensional Arrays Examples 7. Examples Using

More information

CSC 211 Intermediate Programming. Pointers

CSC 211 Intermediate Programming. Pointers CSC 211 Intermediate Programming Pointers 1 Purpose Pointers enable programs to simulate call-by-reference; to create and manipulate dynamic data structures, i.e. data structures that can grow and shrink,

More information

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

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8 Pointers Variables vs. Pointers: A variable in a program is something with a name and a value that can vary. The way the compiler and linker handles this is that it assigns a specific block of memory within

More information

Functions and Recursion

Functions and Recursion Functions and Recursion 1 Storage Classes Scope Rules Functions with Empty Parameter Lists Inline Functions References and Reference Parameters Default Arguments Unary Scope Resolution Operator Function

More information

Fundamentals of Programming Session 19

Fundamentals of Programming Session 19 Fundamentals of Programming Session 19 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

C++ PROGRAMMING SKILLS Part 4: Arrays

C++ PROGRAMMING SKILLS Part 4: Arrays C++ PROGRAMMING SKILLS Part 4: Arrays Outline Introduction to Arrays Declaring and Initializing Arrays Examples Using Arrays Sorting Arrays: Bubble Sort Passing Arrays to Functions Computing Mean, Median

More information

Arrays. Outline. Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Prentice Hall, Inc. All rights reserved.

Arrays. Outline. Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Prentice Hall, Inc. All rights reserved. Arrays 1 Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Multidimensional Arrays 2 Multiple subscripts a[ i ][ j ] Tables with rows and columns Specify row, then column

More information

by Pearson Education, Inc. All Rights Reserved.

by Pearson Education, Inc. All Rights Reserved. Let s improve the bubble sort program of Fig. 6.15 to use two functions bubblesort and swap. Function bubblesort sorts the array. It calls function swap (line 51) to exchange the array elements array[j]

More information

Exercise 1.1 Hello world

Exercise 1.1 Hello world Exercise 1.1 Hello world The goal of this exercise is to verify that computer and compiler setup are functioning correctly. To verify that your setup runs fine, compile and run the hello world example

More information

Chapter 18 - C++ Operator Overloading

Chapter 18 - C++ Operator Overloading Chapter 18 - C++ Operator Overloading Outline 18.1 Introduction 18.2 Fundamentals of Operator Overloading 18.3 Restrictions on Operator Overloading 18.4 Operator Functions as Class Members vs. as friend

More information

Lecture 4. Default Arguments. Set defaults in function prototype. int myfunction( int x = 1, int y = 2, int z = 3 );

Lecture 4. Default Arguments. Set defaults in function prototype. int myfunction( int x = 1, int y = 2, int z = 3 ); Lecture 4 More on functions Default arguments Recursive functions Sorting and Searching (e.g. bubble sort, linear search, binary search) Declaration file (specification), definition file (implementation)

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number

More information

C Functions. Object created and destroyed within its block auto: default for local variables

C Functions. Object created and destroyed within its block auto: default for local variables 1 5 C Functions 5.12 Storage Classes 2 Automatic storage Object created and destroyed within its block auto: default for local variables auto double x, y; Static storage Variables exist for entire program

More information

Introduction. W8.2 Operator Overloading

Introduction. W8.2 Operator Overloading W8.2 Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. as friend Functions Overloading Stream Insertion and Extraction

More information

A pointer is a variable just like other variable. The only difference from other variables is that it stores the memory address other variables.

A pointer is a variable just like other variable. The only difference from other variables is that it stores the memory address other variables. Lecture 9 Pointers A pointer is a variable just like other variable. The only difference from other variables is that it stores the memory address other variables. This variable may be of type int, char,

More information

W8.2 Operator Overloading

W8.2 Operator Overloading 1 W8.2 Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. as friend Functions Overloading Stream Insertion and Extraction

More information

Week 3: Pointers (Part 2)

Week 3: Pointers (Part 2) Advanced Programming (BETC 1353) Week 3: Pointers (Part 2) Dr. Abdul Kadir abdulkadir@utem.edu.my Learning Outcomes: Able to describe the concept of pointer expression and pointer arithmetic Able to explain

More information

Operator Overloading

Operator Overloading Operator Overloading Introduction Operator overloading Enabling C++ s operators to work with class objects Using traditional operators with user-defined objects Requires great care; when overloading is

More information

Operator Overloading in C++ Systems Programming

Operator Overloading in C++ Systems Programming Operator Overloading in C++ Systems Programming Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. Global Functions Overloading

More information

Introduction to C++ Introduction to C++ 1

Introduction to C++ Introduction to C++ 1 1 What Is C++? (Mostly) an extension of C to include: Classes Templates Inheritance and Multiple Inheritance Function and Operator Overloading New (and better) Standard Library References and Reference

More information

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad Outline 1. Introduction 2. Program Components in C++ 3. Math Library Functions 4. Functions 5. Function Definitions 6. Function Prototypes 7. Header Files 8.

More information

0 vs NULL // BBM 101. Introduction to Programming I. Lecture #12 C Pointers & Strings

0 vs NULL // BBM 101. Introduction to Programming I. Lecture #12 C Pointers & Strings 0 vs NULL // Twitter @raysato BBM 101 Introduction to Programming I Lecture #12 C Pointers & Strings Erkut Erdem, Aykut Erdem & Aydın Kaya // Fall 2017 Last time Functions, Loops and M- D Arrays in C Switch

More information

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

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples: 1 Programming in C Pointer Variable A variable that stores a memory address Allows C programs to simulate call-by-reference Allows a programmer to create and manipulate dynamic data structures Must be

More information

MYcsvtu Notes LECTURE 34. POINTERS

MYcsvtu Notes LECTURE 34.  POINTERS LECTURE 34 POINTERS Pointer Variable Declarations and Initialization Pointer variables Contain memory addresses as their values Normal variables contain a specific value (direct reference) Pointers contain

More information

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED Outline - Function Definitions - Function Prototypes - Data

More information

6.5 Function Prototypes and Argument Coercion

6.5 Function Prototypes and Argument Coercion 6.5 Function Prototypes and Argument Coercion 32 Function prototype Also called a function declaration Indicates to the compiler: Name of the function Type of data returned by the function Parameters the

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number Generation

More information

C++ for Java Programmers

C++ for Java Programmers Basics all Finished! Everything we have covered so far: Lecture 5 Operators Variables Arrays Null Terminated Strings Structs Functions 1 2 45 mins of pure fun Introduction Today: Pointers Pointers Even

More information

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c.

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c. Chapter 9: Pointers 9.1 Getting the Address of a Variable C++ Variables [ not in book ] A Variable has all of the following attributes: 1. name 2. type 3. size 4. value 5. storage class static or automatic

More information

Pointers. Variable Declaration. Chapter 10

Pointers. Variable Declaration. Chapter 10 Pointers Chapter 10 Variable Declaration When a variable is defined, three fundamental attributes are associated with it: Name Type Address The variable definition associates the name, the type, and the

More information

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++ Chapter 3 - Functions 1 Chapter 3 - Functions 2 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3. Functions 3.5 Function Definitions 3.6 Function Prototypes 3. Header Files 3.8

More information

Programming for Engineers Pointers

Programming for Engineers Pointers Programming for Engineers Pointers ICEN 200 Spring 2018 Prof. Dola Saha 1 Pointers Pointers are variables whose values are memory addresses. A variable name directly references a value, and a pointer indirectly

More information

C++ Programming Lecture 11 Functions Part I

C++ Programming Lecture 11 Functions Part I C++ Programming Lecture 11 Functions Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department Introduction Till now we have learned the basic concepts of C++. All the programs

More information

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

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 1 7 C Pointers 7.7 sizeof Operator 2 sizeof Returns size of operand in bytes For arrays: size of 1 element * number of elements if sizeof( int ) equals 4 bytes, then int myarray[ 10 ]; printf( "%d", sizeof(

More information

Computer Programming with C++ (21)

Computer Programming with C++ (21) Computer Programming with C++ (21) Zhang, Xinyu Department of Computer Science and Engineering, Ewha Womans University, Seoul, Korea zhangxy@ewha.ac.kr Classes (III) Chapter 9.7 Chapter 10 Outline Destructors

More information

Pointers and Structure. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Pointers and Structure. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island Pointers and Structure Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island 1 Pointer Variables Each variable in a C program occupies space in

More information

BITG 1113: POINTER LECTURE 12

BITG 1113: POINTER LECTURE 12 BITG 1113: POINTER LECTURE 12 1 LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the concept of pointer. 2. Write declaration and initialization of a pointer. 3. Do arithmetic

More information

Tokens, Expressions and Control Structures

Tokens, Expressions and Control Structures 3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type

More information

Homework #3 CS2255 Fall 2012

Homework #3 CS2255 Fall 2012 Homework #3 CS2255 Fall 2012 MULTIPLE CHOICE 1. The, also known as the address operator, returns the memory address of a variable. a. asterisk ( * ) b. ampersand ( & ) c. percent sign (%) d. exclamation

More information

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

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers and Arrays CS 201 This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers Powerful but difficult to master Used to simulate pass-by-reference

More information

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad Outline 1. Introduction 2. Program Components in C++ 3. Math Library Functions 4. Functions 5. Function Definitions 6. Function Prototypes 7. Header Files 8.

More information

What is an algorithm?

What is an algorithm? Announcements CS 142 C++ Pointers Reminder Program 6 due Sunday, Nov. 9 th by 11:55pm 11/3/2014 2 Pointers and the Address Operator Pointer Variables Each variable in a program is stored at a unique address

More information

CS201- Introduction to Programming Current Quizzes

CS201- Introduction to Programming Current Quizzes CS201- Introduction to Programming Current Quizzes Q.1 char name [] = Hello World ; In the above statement, a memory of characters will be allocated 13 11 12 (Ans) Q.2 A function is a block of statements

More information

Exam 3 Chapters 7 & 9

Exam 3 Chapters 7 & 9 Exam 3 Chapters 7 & 9 CSC 2100-002/003 29 Mar 2017 Read through the entire test first BEFORE starting Put your name at the TOP of every page The test has 4 sections worth a total of 100 points o True/False

More information

Classes and Data Abstraction. Topic 5

Classes and Data Abstraction. Topic 5 Classes and Data Abstraction Topic 5 Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes The data and functions of a class

More information

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++ CSCE 206: Structured Programming in C++ 2017 Spring Exam 3 Monday, April 17, 2017 Total - 100 Points B Instructions: Total of 11 pages, including this cover and the last page. Before starting the exam,

More information

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++ CSCE 206: Structured Programming in C++ 2017 Spring Exam 3 Monday, April 17, 2017 Total - 100 Points A Instructions: Total of 11 pages, including this cover and the last page. Before starting the exam,

More information

Functions. Function Prototypes. Function prototype is needed if the function call comes before the function definition in the program.

Functions. Function Prototypes. Function prototype is needed if the function call comes before the function definition in the program. Functions Functions are defined as follows: return-value-type function-name( parameter-list ) { local declarations and statements Example: int square( int y ) { return y * y; 1 Function Prototypes Function

More information

Chapter 2 - Control Structures

Chapter 2 - Control Structures Chapter 2 - Control Structures 1 2.11 Assignment Operators 2.12 Increment and Decrement Operators 2.13 Essentials of Counter-Controlled Repetition 2.1 for Repetition Structure 2.15 Examples Using the for

More information

CHAPTER 2.1 CONTROL STRUCTURES (SELECTION) Dr. Shady Yehia Elmashad

CHAPTER 2.1 CONTROL STRUCTURES (SELECTION) Dr. Shady Yehia Elmashad CHAPTER 2.1 CONTROL STRUCTURES (SELECTION) Dr. Shady Yehia Elmashad Outline 1. The if Selection Structure 2. The if/else Selection Structure 3. The switch Multiple-Selection Structure 1. The if Selection

More information

Week 7: Pointers and Arrays. BJ Furman 02OCT2009

Week 7: Pointers and Arrays. BJ Furman 02OCT2009 Week 7: Pointers and Arrays BJ Furman 02OCT2009 The Plan for Today Closer look at pointers What is a pointer? Why use pointers? How can we use pointers? Pointer Examples Pointer Practice Learning Objectives

More information

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

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables 1 6 C Arrays 6.2 Arrays 2 Array Group of consecutive memory locations Same name and type To refer to an element, specify Array name + position number arrayname[ position number ] First element at position

More information

CSC 330 Object Oriented Programming. Operator Overloading Friend Functions & Forms

CSC 330 Object Oriented Programming. Operator Overloading Friend Functions & Forms CSC 330 Object Oriented Programming Operator Overloading Friend Functions & Forms 1 Restrictions on Operator Overloading Most of C++ s operators can be overloaded. Operators that can be overloaded + -

More information

Operator Overloading

Operator Overloading Operator Overloading Introduction Operator overloading Enabling C++ s operators to work with class objects Using traditional operators with user-defined objects Requires great care; when overloading is

More information

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

What have we learned about when we learned about function parameters? 1-1 What have we learned about when we learned about function parameters? 1-1 What have we learned about when we learned about function parameters? Call-by-Value also known as scalars (eg. int, double, char,

More information

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING Dr. Shady Yehia Elmashad Outline 1. Introduction to C++ Programming 2. Comment 3. Variables and Constants 4. Basic C++ Data Types 5. Simple Program: Printing

More information

Functions and Recursion

Functions and Recursion Functions and Recursion 1 Outline Introduction Program Components in C++ Math Library Functions Functions Function Definitions Function Prototypes Header Files Random Number Generation Example: A Game

More information

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): 1. If a function has default arguments, they can be located anywhere

More information

Introduction to Computer Science Midterm 3 Fall, Points

Introduction to Computer Science Midterm 3 Fall, Points Introduction to Computer Science Fall, 2001 100 Points Notes 1. Tear off this sheet and use it to keep your answers covered at all times. 2. Turn the exam over and write your name next to the staple. Do

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Multiple Inheritance July 26, 2004 22.9 Multiple Inheritance 2 Multiple inheritance Derived class has several base classes Powerful,

More information

Chapter 9. Pointers and Dynamic Arrays

Chapter 9. Pointers and Dynamic Arrays Chapter 9 Pointers and Dynamic Arrays Overview 9.1 Pointers 9.2 Dynamic Arrays Slide 9-2 9.1 Pointers Pointers n A pointer is the memory address of a variable n Memory addresses can be used as names for

More information

1 // Fig. 6.13: time2.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> Outline. 4 5 using std::cout; 6 7 #include <iomanip>

1 // Fig. 6.13: time2.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> Outline. 4 5 using std::cout; 6 7 #include <iomanip> CISC11 Introduction to Computer Science Dr. McCoy Lecture 20 November, 2009. Using Default Arguments with Constructors Constructors Can specify default arguments Default constructors Defaults all arguments

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

A Deeper Look at Classes

A Deeper Look at Classes A Deeper Look at Classes Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by

More information

CMPS 221 Sample Final

CMPS 221 Sample Final Name: 1 CMPS 221 Sample Final 1. What is the purpose of having the parameter const int a[] as opposed to int a[] in a function declaration and definition? 2. What is the difference between cin.getline(str,

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY

DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY Pages 800 to 809 Anna Rakitianskaia, University of Pretoria STATIC ARRAYS So far, we have only used static arrays The size of a static array must

More information