Pointers and Strings. Adhi Harmoko S, M.Komp

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

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

C Pointers. 7.2 Pointer Variable Definitions and Initialization

Chapter 6 - Pointers

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

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

Lecture 05 POINTERS 1

Chapter 5 - Pointers and Strings

Chapter 5 - Pointers and Strings

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

C Pointers Pearson Education, Inc. All rights reserved.

IS 0020 Program Design and Software Tools

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

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

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

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

Arrays. Week 4. Assylbek Jumagaliyev

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

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

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

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

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

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

by Pearson Education, Inc. All Rights Reserved.

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

C++ Programming Chapter 7 Pointers

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

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

0 vs NULL // BBM 101. Introduction to Programming I. Lecture #12 C Pointers & 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

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

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

MYcsvtu Notes LECTURE 34. POINTERS

Functions and Recursion

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

Chapter 18 - C++ Operator Overloading

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

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

C++ PROGRAMMING SKILLS Part 4: Arrays

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

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

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

Week 3: Pointers (Part 2)

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

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

Operator Overloading in C++ Systems Programming

CSC 211 Intermediate Programming. Pointers

Introduction to C++ Systems Programming

Introduction. W8.2 Operator Overloading

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Exercise 1.1 Hello world

W8.2 Operator Overloading

Introduction to C++ Introduction to C++ 1

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

Computer Programming with C++ (21)

Operator Overloading

Chapter 7 C Pointers

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

Pointers. Memory. void foo() { }//return

Chapter 3 - Functions

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

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Programming for Engineers Pointers

BITG 1113: POINTER LECTURE 12

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

Exam 3 Chapters 7 & 9

Chapter 3 - Functions

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Homework #3 CS2255 Fall 2012

C++ Programming Lecture 11 Functions Part I

C++ for Java Programmers

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in 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.

Pointers. 10/5/07 Pointers 1

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

12. Pointers Address-of operator (&)

Pointers, Dynamic Data, and Reference Types

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>

Chapter 3 - Functions

pointers + memory double x; string a; int x; main overhead int y; main overhead

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):

What is an algorithm?

Classes and Data Abstraction. Topic 5

6.5 Function Prototypes and Argument Coercion

A Deeper Look at Classes

BITG 1113: Function (Part 2) LECTURE 5

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

CSC 211 Intermediate Programming. Arrays & Pointers

IS 0020 Program Design and Software Tools

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

IS 0020 Program Design and Software Tools

Lecture on pointers, references, and arrays and vectors

Introduction to C++ Programming. Adhi Harmoko S, M.Komp

More C++ Classes. Systems Programming

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

Fundamentals of Programming Session 20

Pointers. Lecture 1 Sections Robb T. Koether. Hampden-Sydney College. Wed, Jan 14, 2015

C Pointers. 6th April 2017 Giulio Picierro

Transcription:

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 Initialization Pointer variables Contain memory addresses as their values Normal variables contain a specific value (direct reference) Pointers contain the address of a variable that has a specific value (indirect reference) countptr count Indirection Referencing a pointer value Pointer declarations * indicates variable is a pointer int *myptr; declares a pointer to an int, a pointer of type int * Multiple pointers require multiple asterisks int *myptr1, *myptr2; 7 count 7

Pointer Variable Declarations and Initialization Can declare pointers to any data type Pointers initialization Initialized to 0, NULL, or an address 0 or NULL points to nothing

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

Pointer Operators * (indirection/dereferencing operator) Returns the value of what its operand points to *yptr returns y (because yptr points to y). * can be used to assign a value to a location in memory *yptr = 7; // changes y to 7 Dereferenced pointer (operand of *) must be an lvalue (no constants) * and & are inverses Cancel each other out *&myvar == myvar and &*yptr == yptr

Fig. 5.4: fig05_04.cpp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 // Fig. 5.4: fig05_04.cpp // Using the & and * operators. #include <iostream> using std::cout; using std::endl; int main() int a; // a is an integer int *aptr; // aptr is a pointer to an integer a = 7; aptr = &a; // aptr assigned address of a cout << "The address of a is " << &a << "\nthe value of aptr is " << aptr; cout << "\n\nthe value of a is " << a << "\nthe value of *aptr is " << *aptr;

Fig. 5.4: fig05_04.cpp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 // Fig. 5.4: fig05_04.cpp // Using the & and * operators. #include <iostream> using std::cout; using std::endl; The address of a is the value of aptr int main() int a; // a is an integer int *aptr; // aptr is a pointer to an integer a = 7; aptr = &a; // aptr assigned address of a cout << "The address of a is " << &a << "\nthe value of aptr is " << aptr; cout << "\n\nthe value of a is " << a << "\nthe value of *aptr is " << *aptr;

Fig. 5.4: fig05_04.cpp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 // Fig. 5.4: fig05_04.cpp // Using the & and * operators. #include <iostream> using std::cout; using std::endl; int main() int a; // a is an integer int *aptr; // aptr is a pointer to an integer a = 7; aptr = &a; // aptr assigned address of a cout << "The address of a is " << &a << "\nthe value of aptr is " << aptr; cout << "\n\nthe value of a is " << a << "\nthe value of *aptr is " << *aptr; The * operator returns an alias to what its operand points to. aptr points to a, so *aptr returns a.

Fig. 5.4: fig05_04.cpp 22 23 24 25 26 27 28 29 30 cout << "\n\nshowing that * and & are inverses of " << "each other.\n&*aptr = " << &*aptr << "\n*&aptr = " << *&aptr << endl; return 0; // indicates successful termination } // end main

Fig. 5.4: fig05_04.cpp 22 23 24 25 26 27 28 29 30 cout << "\n\nshowing that * and & are inverses of " << "each other.\n&*aptr = " << &*aptr << "\n*&aptr = " << *&aptr << endl; return 0; // indicates successful termination } // end main Notice how * and & are inverses

Fig. 5.4: fig05_04.cpp 22 23 24 25 26 27 28 29 30 cout << "\n\nshowing that * and & are inverses of " << "each other.\n&*aptr = " << &*aptr << "\n*&aptr = " << *&aptr << endl; return 0; // indicates successful termination } // end main The address of a is 006AFDF4 The value of aptr is 006AFDF4 The value of a is 7 The value of *aptr is 7 Showing that * and & are inverses of each other. &*aptr = 006AFDF4 *&aptr = 006AFDF4

Calling Functions by Reference Call by reference with pointer arguments Pass address of argument using & operator Allows you to change actual location in memory Arrays are not passed with & because the array name is already a pointer * operator used as alias/nickname for variable inside of function void doublenum( int *number ) } *number = 2 * ( *number ); *number used as nickname for the variable passed in When the function is called, must be passed an address doublenum( &mynum );

Fig. 5.4: fig05_07.cpp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 // Fig. 5.7: fig05_07.cpp // Cube a variable using pass-by-reference // with a pointer argument. #include <iostream> using std::cout; using std::endl; void cubebyreference( int * ); // prototype int main() int number = 5; cout << "The original value of number is " << number; // pass address of number to cubebyreference cubebyreference( &number ); cout << "\nthe new value of number is " << number << endl; return 0; // indicates successful termination } // end main

Fig. 5.4: fig05_07.cpp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 // Fig. 5.7: fig05_07.cpp // Cube a variable using pass-by-reference // with a pointer argument. #include <iostream> using std::cout; using std::endl; void cubebyreference( int * ); // prototype int main() int number = 5; cout << "The original value of number is " << number; // pass address of number to cubebyreference cubebyreference( &number ); cout << "\nthe new value of number is " << number << endl; return 0; // indicates successful termination } // end main Notice how the address of number is given - cubebyreference expects a pointer (an address of a variable).

Fig. 5.4: fig05_07.cpp 24 25 26 27 28 29 30 31 // calculate cube of *nptr; modifies variable number in main void cubebyreference( int *nptr ) *nptr = *nptr * *nptr * *nptr; // cube *nptr } // end function cubebyreference

Fig. 5.4: fig05_07.cpp 24 25 26 27 28 29 30 31 // calculate cube of *nptr; modifies variable number in main void cubebyreference( int *nptr ) *nptr = *nptr * *nptr * *nptr; // cube *nptr } // end function cubebyreference Inside cubebyreference, *nptr is used (*nptr is number).

Fig. 5.4: fig05_07.cpp 24 25 26 27 28 29 30 31 // calculate cube of *nptr; modifies variable number in main void cubebyreference( int *nptr ) *nptr = *nptr * *nptr * *nptr; // cube *nptr } // end function cubebyreference The original value of number is 5 The new value of number is 125

Using the Const Qualifier with Pointers const qualifier Variable cannot be changed const used when function does not need to change a variable Attempting to change a const variable is a compiler error const pointers Point to same memory location Must be initialized when declared int *const myptr = &x; Constant pointer to a non-constant int const int *myptr = &x; Non-constant pointer to a constant int const int *const Ptr = &x; Constant pointer to a constant int

Fig. 5.4: fig05_13.cpp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 // Fig. 5.13: fig05_13.cpp // Attempting to modify a constant pointer to // non-constant data. int main() int x, y; // ptr is a constant pointer to an integer that can // be modified through ptr, but ptr always points to the // same memory location. int * const ptr = &x; *ptr = 7; // allowed: *ptr is not const ptr = &y; // error: ptr is const; cannot assign new address return 0; // indicates successful termination } // end main

Fig. 5.4: fig05_13.cpp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 // Fig. 5.13: fig05_13.cpp // Attempting to modify a constant pointer to // non-constant data. int main() int x, y; // ptr is a constant pointer to an integer that can // be modified through ptr, but ptr always points to the // same memory location. int * const ptr = &x; *ptr = 7; // allowed: *ptr is not const ptr = &y; // error: ptr is const; cannot assign new address return 0; // indicates successful termination } // end main Changing *ptr is allowed - x is not a constant.

Fig. 5.4: fig05_13.cpp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 // Fig. 5.13: fig05_13.cpp // Attempting to modify a constant pointer to // non-constant data. int main() int x, y; // ptr is a constant pointer to an integer that can // be modified through ptr, but ptr always points to the // same memory location. int * const ptr = &x; *ptr = 7; // allowed: *ptr is not const ptr = &y; // error: ptr is const; cannot assign new address return 0; // indicates successful termination } // end main Changing ptr is an error - ptr is a constant pointer. Error E2024 Fig05_13.cpp 15: Cannot modify a const object in function main()

Bubble Sort Using Call-by-reference Implement bubblesort using pointers swap function must receive the address (using &) of the array elements array elements have call-by-value default Using pointers and the * operator, swap is able to switch the values of the actual array elements Psuedocode Initialize array print data in original order Call function bubblesort print sorted array Define bubblesort

Bubble Sort Using Call-by-reference sizeof Returns size of operand in bytes For arrays, sizeof returns ( the size of 1 element ) * ( number of elements ) if sizeof( int ) = 4, then int myarray[10]; cout << sizeof(myarray); will print 40 sizeof can be used with Variable names Type names Constant values

Fig. 5.4: fig05_15.cpp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 // Fig. 5.15: fig05_15.cpp // This program puts values into an array, sorts the values into // ascending order, and prints the resulting array. #include <iostream> using std::cout; using std::endl; #include <iomanip> using std::setw; void bubblesort( int *, const int ); // prototype void swap( int * const, int * const ); // prototype int main() const int arraysize = 10; int a[ arraysize ] = 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; cout << "Data items in original order\n";

Fig. 5.4: fig05_15.cpp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 // Fig. 5.15: fig05_15.cpp // This program puts values into an array, sorts the values into // ascending order, and prints the resulting array. #include <iostream> using std::cout; using std::endl; #include <iomanip> using std::setw; void bubblesort( int *, const int ); // prototype void swap( int * const, int * const ); // prototype int main() const int arraysize = 10; int a[ arraysize ] = 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; cout << "Data items in original order\n"; Bubblesort gets passed the address of array elements (pointers). The name of an array is a pointer.

Fig. 5.4: fig05_15.cpp 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 for ( int i = 0; i < arraysize; i++ ) cout << setw( 4 ) << a[ i ]; bubblesort( a, arraysize ); // sort the array cout << "\ndata items in ascending order\n"; for ( int j = 0; j < arraysize; j++ ) cout << setw( 4 ) << a[ j ]; cout << endl; return 0; // indicates successful termination } // end main

Fig. 5.4: fig05_15.cpp 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 // sort an array of integers using bubble sort algorithm void bubblesort( int *array, const int size ) // loop to control passes for ( int pass = 0; pass < size - 1; pass++ ) // loop to control comparisons during each pass for ( int k = 0; k < size - 1; k++ ) // swap adjacent elements if they are out of order if ( array[ k ] > array[ k + 1 ] ) swap( &array[ k ], &array[ k + 1 ] ); } // end function bubblesort // swap values at memory locations to which // element1ptr and element2ptr point void swap( int * const element1ptr, int * const element2ptr ) int hold = *element1ptr; *element1ptr = *element2ptr; *element2ptr = hold; } // end function swap

Fig. 5.4: fig05_15.cpp 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 // sort an array of integers using bubble sort algorithm void bubblesort( int *array, const int size ) // loop to control passes for ( int pass = 0; pass < size - 1; pass++ ) // loop to control comparisons during each pass for ( int k = 0; k < size - 1; k++ ) // swap adjacent elements if they are out of order if ( array[ k ] > array[ k + 1 ] ) swap( &array[ k ], &array[ k + 1 ] ); } // end function bubblesort // swap values at memory locations to which // element1ptr and element2ptr point void swap( int * const element1ptr, int * const element2ptr ) int hold = *element1ptr; *element1ptr = *element2ptr; *element2ptr = hold; } // end function swap swap takes pointers (addresses of array elements) and dereferences them to modify the original array elements.

Fig. 5.4: fig05_15.cpp Data items in original order 2 6 4 8 10 12 89 68 45 37 Data items in ascending order 2 4 6 8 10 12 37 45 68 89