Lecture 6 C++ Programming

Slides:



Advertisements
Similar presentations
Lectures 10 & 11.
Advertisements

What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Kernighan/Ritchie: Kelley/Pohl:
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Pointers Discussion 5 Section Housekeeping HW 1 Issues Array Issues Exam 1 Questions? Submitting on Time!
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic.
Pointers| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2006 Slide 1 Pointers by Jumail Bin Taliba Faculty of Computer.
Pointers CSE 2451 Rong Shi.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
CSC 2400 Computer Systems I Lecture 5 Pointers and Arrays.
1 Pointers and Strings Chapter 5 2 What You Will Learn...  How to use pointers Passing arguments to functions with pointers See relationship of pointers.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Pointers.
Lecture 10 Introduction to Programming in C Prof. Dr. Arne Kutzner Hanyang University / Seoul Korea.
1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Lecture 6 C++ Programming Arne Kutzner Hanyang University / Seoul Korea.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Pointers *, &, array similarities, functions, sizeof.
© Oxford University Press All rights reserved. CHAPTER 7 POINTERS.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
1 Chapter 7 Pointers and C-Strings. 2 Objectives  To describe what a pointer is (§7.1).  To learn how to declare a pointer and assign a value to it.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Pointers Lecture: 5. Topics 1 Pointers and the Address Operator 2 Pointer Variables 3 The Relationship Between Arrays and Pointers 4 Pointer Arithmetic.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
1 Memory, Arrays & Pointers. Memory 2 int main() { char c; int i,j; double x; cijx.
Topic 5 Addresses, Pointers and Arrays. 2 Objectives (Textbook Chapter 14) You should be able to describe: Addresses and Pointers Pointer Operators Pointer.
Overview Working directly with memory locations is beneficial. In C, pointers allow you to: change values passed as arguments to functions work directly.
Lecture 5 Pointers 1. Variable, memory location, address, value
Stack and Heap Memory Stack resident variables include:
Chapter 7 Pointers and C-Strings
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
UNIT 5 C Pointers.
Standard Version of Starting Out with C++, 4th Edition
Chapter 9: Pointers.
Pointers and Pointer-Based Strings
Programming Languages and Paradigms
8 Pointers.
Andy Wang Object Oriented Programming in C++ COP 3330
Dynamic Memory Allocation
Object Oriented Programming COP3330 / CGS5409
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
Pointers, Dynamic Data, and Reference Types
Lecture 18 Arrays and Pointer Arithmetic
Pointers.
Outline Defining and using Pointers Operations on pointers
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
Chapter 16 Pointers and Arrays
C++ Pointers and Strings
Pointers Pointers point to memory locations
Pointers and Pointer-Based Strings
Data Structures and Algorithms Introduction to Pointers
Standard Version of Starting Out with C++, 4th Edition
Pointers and References
CISC181 Introduction to Computer Science Dr
C++ Pointers and Strings
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

Lecture 6 C++ Programming Arne Kutzner Hanyang University / Seoul Korea

Function overloading

Function Overloading Two functions have the same name Functions can be distinguished by types of function header Example: double max(double num1, double num2) { if (num1 > num2) return num1; else return num2; } Same name but different types int max(int num1, int num2) { if (num1 > num2) return num1; else return num2; } C++ Programming

Function Overloading During compile time we can select the appropriate definition of a overloaded function double max(double num1, double num2) { if (num1 > num2) return num1; else return num2; } d = max(2.0, 3.0); i = max(2, 3); int max(int num1, int num2) { if (num1 > num2) return num1; else return num2; } C++ Programming

Warning: Ambiguous Invocation Sometimes there may be two or more possible matches for an invocation of a method, but the compiler cannot determine the most specific match. This is referred to as ambiguous invocation. Ambiguous invocation is a compilation error, but can be resolved by a type-cast. C++ Programming

Ambiguous Invocation Example double max(int num1, double num2) { if (num1 > num2) return num1; else return num2; } double max(double num1, int num2) { ? d = max(4.0, 5.0); C++ Programming

Pointers / Introduction

Variables and Memory Address Every variable has some location in the memory that holds the value of the variable. This location is called the address of the variable. 1000 1004 1008 1012 1016 1020 num The address of the variable num int num = 0; C++ Programming

Pointers A pointer is also a variable, but unlike the other types of variables that we have seen, it contains a memory address as its value. C++ Programming

Pointer Declaration int *p; To declare a pointer variable, a asterisk(*) should placed in front of name of the name of the variable. Example: int *p; p is a pointer to an integer value (i.e. p contains the address of some memory cell that contains an integer value) C++ Programming

Address Operator You can get the memory address of some variable by using the address operator &. Example: int x = 0; int *p; p = &x; 1000 1004 1008 1012 1016 1020 x p The pointer p gets the address of the variable x as its value C++ Programming

How to dereference pointers? For dereferencing a pointer place a asterisk in front of the pointer variable name. Example: int x = 0; int *p; p = &x; *p = 5; 1000 5 1004 1008 1012 1016 1020 x p Write the value 5 to the memory location referenced by p C++ Programming

Pointer Types Pointers can be declared to point to variables of any type. Examples: int *p1; pointer to an integer double *p2; pointer to a floating point number char *p3; pointer to a character C++ Programming

Example Program 1 int main() { … int x1 = 5; int x2 = 8; int *x1ptr; x1ptr = &x1; x2ptr = &x2; *x2ptr = 12; } x1 5 1000 x2 8 1004 x1ptr ? 1008 x2ptr 1012 x1 5 1000 x2 8 1004 x1ptr 1008 x2ptr 1012 x1 5 1000 x2 12 1004 x1ptr 1008 x2ptr 1012 C++ Programming

Example Program 2 The resulting memory picture 1 int main() { 2 int num1, num2, product; 3 int *ptr_num1, *ptr_num2; 4 num1 = 5; 5 num2 = 7; 6 ptr_num1 = &num1; 7 ptr_num2 = &num2; 8 product = num1 * (*ptr_num2); … } num1 5 1000 num2 7 1004 product 35 1008 ptr_num1 1012 ptr_num2 1014 * operator specifies dereferencing a pointer * operator specifies multiplication C++ Programming

Pointer type equivalence A pointer can dereference only a variable which is of the same type. Example: int n = 5; double x = 5.0; int *ptr1; double *ptr2; ptr1 = &n; ptr2 = &n; ptr1 = &x; Compile error! ptr1 is a pointer to integer whereas x is a floating point number. ptr2 is a pointer to double whereas n is an integer number. C++ Programming

Warning: Uninitialized Pointers Dereferencing a pointer that has not been properly initialized Example: int *p; *p = 1; printf("Value is %d", *p); The pointer contains an arbitrary address, so *p=1 may overwrite some arbitrary location in memory which can cause severe problems. C++ Programming

Effects with uninitialized/wrong pointers Program attempts to access some random memory location. Possible effects: Fatal Runtime error (common program run-time error message: "segmentation fault"). Accidentally modifying other data / variables. Program continues but delivers incorrect result. C++ Programming

Functions and Pointers

Pointers and Functions Function arguments can be of some “pointer type”. Example: void main () { int i; fun (&i); std::cout << i; } void fun (int *p) { *p = 1; } Type of function arguments is “pointer to int” C++ Programming

Call by Reference In the example on the slide before the statement *p = 1 in fun changes the value of i defined main in. Because p refers i in fun we call this form of argument passing call by reference. C++ Programming

Example for the Application of Call by Reference A function fun shall have two input arguments and two output argument. For call by reference we can use in C++ reference parameter as well as pointers x x + y fun Input Output y x * y C++ Programming

Application of Call by Reference The addresses of sum and product are passed as arguments. int main() { int x, y, sum, product; x = 3; y = 5; fun (x, y, &sum, &product) } void fun (int a, int b, int *p1, int *p2) { *p1 = a + b; *p2 = a * b; } C++ Programming

Application of Call by Reference In the previous example, the addresses (not values) of the variables sum and product are copied to the function pointer arguments p1 and p2. In this way, sum and product have the same memory locations as *p1 and *p2, respectively. x 3 y 5 p1 1476 product 15 1468 p2 sum 8 …. a b C++ Programming

Comparison of Call by Reference and Call by Value With the function call by value, the values of the function arguments can't be modified by the function. With the function call by reference, the function arguments are the addresses, not the values of the corresponding variables. These addresses are copied into some pointers which are function arguments. Therefore, modifying the values stored in the addresses pointed by these pointers modifies also the values of the variables. C++ Programming

Comparison of Call by Reference and Call by Value What outputs do we get and why? Call by value … int n = 1; int m = 2; swap(n, m); Std::cout << n << " " << m; … void swap(int x, int y) int temp = x; x = y; y = temp; } Call by reference … swap(&n, &m); std::cout << n << " " << m; void swap(int *p1, int *p2) int temp = *p1; *p1 = *p2; *p2 = temp; C++ Programming

Pointers and Arrays / Pointer Arithmetic

Pointers and Arrays In C there is a strong relationship between the concepts of pointers and arrays An array name is basically a const pointer. (A pointer with fixed address) int *x; int a[10]; x = a; This statement is OK!!! It assigns x the address of the first elements array a. C++ Programming

Pointers and Arrays (cont.) You can even use the [ ] operator with a pointer: int *x; int a[10]; x = a; std::cout << x[2]; x gets “the address of the first element of a” is identical to a[2] C++ Programming

Pointer arithmetic Integer math operations can be used with pointers. If you increment a pointer, it will be increased by the size of whatever it points to. int *ptr = a; *(ptr+2) *(ptr+4) *ptr a[0] a[1] a[2] a[3] a[4] int a[5]; C++ Programming

printing an array void print_array(int a[], int len) { array version for (int i = 0;i < len; i++) std::cout << i << " " << a[i]; } array version void print_array(int *a, int len) { for (int i = 0;i < len; i++) std::cout << i << " " << *a++; } pointer version C++ Programming

Arrays of Pointers Like for any other type you can create arrays of pointers: int a[] = {0, 1, 2}; int b[] = {4, 5, 6}; int* x[2]; x[0] = a; x[1] = b; std::cout << *(x[1]+1); Std::cout << *(*(x+1)+1); x is array of pointers both statements are identical C++ Programming

Matrices and Pointers … The technique can be extended to multidimensional arrays: int a[2][3] = {{0, 1, 2}, {4, 5, 6}}; int* x[2]; x[0] = a[0]; x[1] = a[1]; std::cout << *(x[1]+1); std::cout << *(*(x+1)+1); std::cout << a[1][1]; std::cout << *(a[1]+1); std::cout << *(*(a+1)+1); all statements deliver the same element C++ Programming

Pointers to Pointers Pointer can refer pointers … int *x; int **y; x some int int *x; int **y; y some *int some int C++ Programming

Mixed Topics … C-Strings in C++/ The Heap / Dynamic Memory Allocation /

C strings in C++ A string is a null terminated array of characters. null terminated means there is a character at the end of the the array that has the value 0 (null). Pointers are often used with strings: char *msg = "RPI"; zero (null) msg 'R' 'P' 'I' C++ Programming

String Example - Count the chars int count_string( char *s) { int n=0; while (*s) { n++; s++; } return(n); while the thing pointed to by s is not null increment count set s to point to the next char C++ Programming

Another way int count_string(char *s) { char *ptr = s; while (*ptr) { ptr++; } return(ptr - s); pointer arithmetic! C++ Programming

sizeof(...) function Using the sizeof function we can get the number of bytes consumed by instances of some datatype Syntax: sizeof(<datatype name>); Example: std::cout << sizeof(int); C++ Programming

The Heap The Heap is a special area of memory that allows the dynamic allocation of memory during Runtime. Possible Application: Arrays with dynamic size, e.g. arrays where we know the size only during runtime (Remember: So far we have to specify the size (number of elements) of some array in the context of its declaration. E.g.: x[10]) C++ Programming

Heap Management in C We will later learn a second form of heap management in C++ Old C-style heap management: Three functions for heap management defined in stdlib.h calloc(n, el_size) – allocation of continuous space for an array of n elements with el_size bytes for each array element malloc(size) – allocation of an area of size bytes in the heap free(p) – freeing of allocated heap-space. (C stores internally the amount of memory associated with p) C++ Programming

“void” pointers in C and C++ The following code triggers an error message in C++ but not in C void* fun () { return NULL; } void main() { int *p; p = fun(); } C++ Programming