Array and Pointers An Introduction Unit - 02. Unit Introduction This unit covers the usage of pointers and arrays in C++

Slides:



Advertisements
Similar presentations
Chapter 9 Pointers and Dynamic Arrays. Overview 9.1 Pointers 9.2 Dynamic Arrays.
Advertisements

Programming and Data Structure
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.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
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.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Pointer. Warning! Dangerous Curves C (and C++) have just about the most powerful, flexible and dangerous pointers in the world. –Most other languages.
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
Pointers A pointer is a variable that contains memory address as its value. A variable directly contains a specific value. A pointer contains an address.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
1 ES 314 Advanced Programming Lec 3 Sept 8 Goals: complete discussion of pointers discuss 1-d array examples Selection sorting Insertion sorting 2-d arrays.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Java and C++, The Difference An introduction Unit - 00.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Pointers CS362. Pointers A Pointer is a variable that can hold a memory address Pointers can be used to: Indirectly reference existing variables (sometimes.
C Tokens Identifiers Keywords Constants Operators Special symbols.
Arrays in C++ Numeric Character. Structured Data Type A structured data type is a type that stores a collection of individual components with one variable.
1 Pointers Arrays have a disadvantage: Their size must be known at compile time. We would like the capability to allocate an array-like object of any needed.
Parameter Passing Mechanisms Reference Parameters Read § §
CSC 107 – Programming For Science. Today’s Goal  When lecture over, start understanding pointers  What a pointer is and what it is not  Why pointers.
CSC 107 – Programming For Science. Today’s Goal  When lecture over, start understanding pointers  What a pointer is and what it is not  Why pointers.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Parameter Passing Mechanisms Reference Parameters § §
Dynamic memory allocation and Pointers Lecture 4.
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.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Pointers A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
Introduction to C Programming Lecture 6. Functions – Call by value – Call by reference Arrays Today's Lecture Includes.
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
Pointers *, &, array similarities, functions, sizeof.
© Oxford University Press All rights reserved. CHAPTER 7 POINTERS.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved This Weeks Topics: Pointers (continued)  Modify C-String through a function call 
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
Variables and memory addresses
COMPUTER PROGRAMMING. Array C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
1 2/2/05CS250 Introduction to Computer Science II Pointers.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
© M. Gross, ETH Zürich, 2014 Informatik I für D-MAVT (FS 2014) Exercise 7 – Pointers.
Multi-dimensional Array 1 Multi-dimensional array refers to an array with more than one index. It is a logical representation. On physical storage, the.
CS 31 Discussion, Week 7 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:30-1:30pm.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9-1 Pointer Variables Pointer variable : Often just called a pointer, it's.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
Pointers. What Is Pointer l every variable has memory address char c=’y’; int i=2; address of variable i is 0022 l address can used to refer to this variable.
Windows Programming Lecture 03. Pointers and Arrays.
Pointers A variable that holds an address value is called a pointer variable, or simply a pointer.  What is the data type of pointer variables? It’s not.
UNIT 5 C Pointers.
Pointers and Pointer-Based Strings
Student Book An Introduction
INC 161 , CPE 100 Computer Programming
Chapter 9: Pointers.
C++ fundamentals Lecture 1, Chapter 2 – pp /22/2018 Y K Choi.
Pointers Lecture 2 Tue, Jan 24, 2006.
Pointers and Pointer-Based Strings
C Programming Pointers
Chapter 9: Pointers and String
Structure (i.e. struct) An structure creates a user defined data type
Presentation transcript:

Array and Pointers An Introduction Unit - 02

Unit Introduction This unit covers the usage of pointers and arrays in C++

Unit Objectives After covering this unit you will understand… Arrays in C++ Arrays in C++ Pointers in C++ Pointers in C++ Using pointers Using pointers Pointer Arithmetic Pointer Arithmetic Pointer constants, variables and strings Pointer constants, variables and strings Function Pointers Function Pointers

Array and Pointer An Array is a collection of contiguous memory blocks of same data type An Array is a collection of contiguous memory blocks of same data type An Array has a name, which is the address of the first memory block An Array has a name, which is the address of the first memory block A Pointer is a variable, which holds the address of another variable A Pointer is a variable, which holds the address of another variable

Arrays Array index starts at zero (0) Array index starts at zero (0) int array[10]; // reserves space for 10 int types in memory from 0 to 9 Accessing elements from an array Accessing elements from an array int y = array[0]; // Here, first element is retrieved Storing values in an array Storing values in an array array[4] = 5; // Here the 5th element is given value 5 array[4] = 5; // Here the 5th element is given value 5 Arrays are extremely fast since they are indexed Arrays are extremely fast since they are indexed An Array size cannot be changed at runtime An Array size cannot be changed at runtime

Example: Arrays // This program stores numbers from 0 to 9 in an array #include #include void main() { int array[10]; int array[10]; for (int j=0; j<=9; j++) for (int j=0; j<=9; j++) { array[j] = j; array[j] = j; }}

Pointers Pointers point to a memory space Pointers point to a memory space Pointers are denoted by ‘*’ e.g. Pointers are denoted by ‘*’ e.g. int a = 47; int a = 47; int* pointerToA = &a;

Example: Pointers #include #include void function(int* pointer) { cout << "p = " << *pointer << endl; // prints 4 cout << "p = " << *pointer << endl; // prints 4 *pointer = 6; *pointer = 6; cout << "p = " << *pointer << endl; // prints 6 cout << "p = " << *pointer << endl; // prints 6} void main() { int x = 4; int x = 4; function(&x);// pass the address to the function function(&x);// pass the address to the function cout << "x = " << x << endl; //prints 6 cout << "x = " << x << endl; //prints 6}

Pointer Arithmetic Pointer arithmetic is a special type of arithmetic Pointer arithmetic is a special type of arithmetic int* p; p++; // adds 2-bytes to the pointer address, since type // is int // is int double* pd; pd++; // adds 4-bytes to the pointer address,since type is // double Similar case for classes and structs Similar case for classes and structs The compiler knows how many bytes to go forward The compiler knows how many bytes to go forward

Allowed Pointer Arithmetic Following are the allowed pointer operations: Following are the allowed pointer operations: Subtraction of pointers results in the number of elements between the pointers Subtraction of pointers results in the number of elements between the pointers Addition of integral values in pointers Addition of integral values in pointers Add or subtract pointers with an integral value Add or subtract pointers with an integral value Adding two pointers is not allowed Adding two pointers is not allowed

Example: Pointer Arithmetic #include #include void main() { int* p1; // simple way of defining pointers int* p1; // simple way of defining pointers int* p2; int* p2; int* p3; int* p3; int x; int x; p2 = &x; p2 = &x; p1 = p2; p1 = p2; p2 = p2 + 5; p2 = p2 + 5; cout << (p2 - p1);// prints the number of elements // between the two pointers, which is 5 cout << (p2 - p1);// prints the number of elements // between the two pointers, which is 5 // p3 = p2 + p1; is illegal operation // p3 = p2 + p1; is illegal operation}

Constants and Variables Pointers are variables by default Pointers are variables by default Constant Pointers can be declared by using the const keyword Constant Pointers can be declared by using the const keyword int intVal = 10; int intVal = 10; int* const intPointer = &intVal; /* intPointer is a pointer, which is const, that points to /* intPointer is a pointer, which is const, that points to an int */ an int */ In the above example you can change the value in intVal but not the address In the above example you can change the value in intVal but not the address *intPointer = 20; /* allowed because the pointer (i.e. the address) is constant, while the value inside the pointer can be variable */ /* allowed because the pointer (i.e. the address) is constant, while the value inside the pointer can be variable */

Example: Constants & Variables #include #include void main() { int b = 25; int b = 25; /* (shown below) an int pointer that is stored at a /* (shown below) an int pointer that is stored at a constant memory address */ constant memory address */ int* const a = &b; // ‘a’ holds the address of ‘b’ // which has a value of 25 int* const a = &b; // ‘a’ holds the address of ‘b’ // which has a value of 25 b = 35; // ‘a’ still points to ‘b’ which now has 35 b = 35; // ‘a’ still points to ‘b’ which now has 35 *a = 45; // allowed - since the value can change // inside the address that the pointer points // to *a = 45; // allowed - since the value can change // inside the address that the pointer points // to}

Array as arguments Arrays are passed by reference in functions Arrays are passed by reference in functions Arrays can’t be passed by value Arrays can’t be passed by value

Example: Array as arguments #include #include function(int* array) { // you can use int array[] as arg // you can use int array[] as arg // do something with the array // do something with the array} void main() { int array[3] = { 1, 2, 3 }; int array[3] = { 1, 2, 3 }; function(array); // any changes made in array inside the function(array); // any changes made in array inside the } // function are reflected in the array

Pointers and String in C++ String declaration in C++ String declaration in C++ As an array // char charArray[10]; As an array // char charArray[10]; As a char* // char* charString; As a char* // char* charString; As a string // string stringTypeArray; As a string // string stringTypeArray; Array of pointers declaration e.g. Array of pointers declaration e.g. char* arrayOfPointers[10]; // array of 10 pointers for (int j=0; j<10; j++) { arrayOfPointers[j] = strcat(“String ”, j); arrayOfPointers[j] = strcat(“String ”, j);}

Function Pointers Pointer that can hold function addresses is called Function Pointer Pointer that can hold function addresses is called Function Pointer Steps required are Steps required are Define a function pointer Define a function pointer Initialise the pointer with function address Initialise the pointer with function address Call the function by using pointer Call the function by using pointer While defining a function pointer, parenthesis are required otherwise it becomes function declaration While defining a function pointer, parenthesis are required otherwise it becomes function declaration

Example: Function Pointer void func() { cout << "func() called..." << endl; cout << "func() called..." << endl;} int main() { void (*fp)(); // define a function pointer void (*fp)(); // define a function pointer fp = func; // Initialise it, assign function address fp = func; // Initialise it, assign function address (*fp)(); // call function using function pointer (*fp)(); // call function using function pointer}

Complex Function Pointers A function pointer can hold address of another pointer to a function, e.g. A function pointer can hold address of another pointer to a function, e.g. double ((*fp1)(int))(float)); double ((*fp1)(int))(float)); fp1 is a pointer to a function that takes an integer argument and returns a pointer to another function that takes a float and returns double fp1 is a pointer to a function that takes an integer argument and returns a pointer to another function that takes a float and returns double

Array of Function Pointers Like array of simple pointers, there can also be array of function pointers Like array of simple pointers, there can also be array of function pointers Useful for table-driven code implementation Useful for table-driven code implementation Instead of using if-else or case statements use a state variable Instead of using if-else or case statements use a state variable

Example: Array of Function Pointers // define functions a(), b() and c() void func1() { cout << ”func1() called..." << endl; cout << ”func1() called..." << endl;} void func2() { cout << ”func2() called..." << endl; cout << ”func2() called..." << endl;} void func3() { cout << ”func3() called..." << endl; cout << ”func3() called..." << endl;} // func_table is an array of function pointers to functions that accept nothing and return void // initialise array with function addresses void (*func_table[])() = {func1, func2, func3 };

Example: Array of Function Pointers (contd.) void main() { cout << ”Enter a number (1-3) to call a function: “; int n; cin >> n; if (n 3) { cout << “Invalid number,should be 1-3” << endl; } // call function using function pointer (*func_table[n-1]();// n is a state variable }

Unit Summary In this unit you have covered … Arrays Arrays Pointers Pointers Uses of Pointers Uses of Pointers