UNIT 9: Pointers Data Variable and Pointer Variable Pass by Reference

Slides:



Advertisements
Similar presentations
Computer Programming Lecture 14 C/C++ Pointers
Advertisements

Chapter 1 C++ Basics. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 1-2 Learning Objectives Introduction to C++ Origins, Object-Oriented.
Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
Data Structures Using C++ 2E
Pointers. 2 A pointer is a variable that points to or references a memory location in which data is stored. Each memory cell in the computer has an address.
Senem KUMOVA METİN CS FALL 1 POINTERS && ARRAYS CHAPTER 6.
Programming and Data Structure
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Pointers Pointer Arithmetic Dale Roberts, Lecturer Computer.
BBS514 Structured Programming (Yapısal Programlama)1 Pointers.
1 Pointers Lecture Introduction Pointers  Powerful, but difficult to master  Simulate pass-by-reference  Close relationship with arrays and.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Kernighan/Ritchie: Kelley/Pohl:
Pointers and Strings. Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close relationship with arrays and strings.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 - Pointers Outline 7.1Introduction 7.2Pointer.
Lesson 6 - Pointers Outline Introduction Pointer Variable Declarations and Initialization Pointer Operators Calling Functions by Reference Using the const.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 7 - Pointers Outline 7.1Introduction 7.2Pointer Variable Declarations and Initialization 7.3Pointer.
Pointers Pointer - A pointer is a derived data type; that is it is a data type built from one of the standard types. Its value is any of the addresses.
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.
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
CS 61C L03 C Arrays (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #3: C Pointers & Arrays
Lecture 7 C Pointers Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Pointers Applications
Computer Skills2 for Scientific Colleges 1 Pointers in C++ Topics to cover: Overview of Pointers Pointer Declaration Pointer Assignment Pointer Arithmetic.
Pointers CSE 2451 Rong Shi.
 2007 Pearson Education, Inc. All rights reserved C Pointers.
CSC 2400 Computer Systems I Lecture 5 Pointers and Arrays.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
(continue) © by Pearson Education, Inc. All Rights Reserved.
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.
[S. Uludag] CIS / CSC 175 Problem Solving and Programming I Winter 2010 Suleyman Uludag Department of Computer Science, Engineering and Physics (CSEP)
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:
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
 2008 Pearson Education, Inc. All rights reserved Pointers and Pointer-Based Strings.
 2000 Deitel & Associates, Inc. All rights reserved Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close.
Pointers Programming Applications. Pointer A pointer is a variable whose value is a memory address representing the location of the chunk of memory on.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 - Pointers Outline 7.1Introduction 7.2Pointer.
Pointers *, &, array similarities, functions, sizeof.
© Oxford University Press All rights reserved. CHAPTER 7 POINTERS.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
1 Lecture 12 Pointers and Strings Section 5.4, ,
DCT1063 Programming 2 CHAPTER 1 POINTERS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
1 Object-Oriented Programming Using C++ A tutorial for pointers.
1 Lecture 8 Pointers and Strings: Part 2 Section 5.4, ,
1. Pointers –Powerful, but difficult to master –Simulate pass-by-reference –Close relationship with arrays and strings 2.
 2003 Prentice Hall, Inc. All rights reserved. 1 Lecture 5: Pointer Outline Chapter 5 Pointer continue Call by reference Pointer arithmatic Debugging.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Pointers in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Chapter 7 Pointers Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
C++ Programming Lecture 18 Pointers – Part II The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
Computer Organization and Design Pointers, Arrays and Strings in C
Computer Skills2 for Scientific Colleges
Chapter 7 - Pointers Outline 7.1 Introduction
Chapter 7 - Pointers Outline 7.1 Introduction
CSC113: Computer Programming (Theory = 03, Lab = 01)
Pointers and Pointer-Based Strings
Computer Skills2 for Scientific Colleges
Pointers Kingdom of Saudi Arabia
5.1 Introduction Pointers Powerful, but difficult to master
CISC181 Introduction to Computer Science Dr
Programming fundamentals 2 Chapter 3:Pointer
Presentation transcript:

UNIT 9: Pointers Data Variable and Pointer Variable Pass by Reference Pointer Arithmetic Passing Array Using Pointers Dynamic Allocation

Address VS. Value Each memory cell could store some VALUE. Each cell has an ADDRESS associated with it. Note: Don’t confuse the address referring to a memory location with the value stored in that location.

Pointer Just another C variable whose value is an address of another variable. “Points to” that other variable.

Declaring a pointer Syntax: Examples: <data_type > *<pointer_name>; Examples: int *ptr; char *cp; float *fp; Note: <data_type > is the type of the data the pointer points to.

Declaring a pointer After declaring a pointer: int *ptr; ptr doesn’t actually point to anything yet. (null pointer) We can either: make it point to something that already exists allocate room in memory for something new that it will point to

Declaring a pointer Declaring a pointer just allocates space to hold the pointer; it does not allocate something to be pointed to. If local variables in C are not initialized, they may contain anything.

Operators Associated with Pointers Reference operator (&) Also known as the address operator Read as “address of” Dereference operator (*) Read as ”value pointed by”

Reference Operator (&) The address that locates a variable within memory is what we call a reference to that variable. Example: int andy; int *ted; ted = &andy;

Reference Operator (&) Example: andy = 25; fred = andy; ted = &andy;

Dereference Operator (*) Using a pointer we can directly access the value stored in the variable which it points to. Example: beth = *ted; /* beth is equal to value pointed by ted */

Dereference Operator (*) Differentiate: beth = ted; /* beth equal to ted ( 1776 ) */ beth = *ted; /* beth equal to value pointed by ted ( 25 ) */ Note: Reference and dereference operators have complementary (or opposite) meanings. A variable referenced with & can be dereferenced with *.

Pointers Examples: andy = 25; ted = &andy; After these expressions:

Pointers Data Variable int x=5; Pointer Variable x=5 &x x=5 address int *p; p=&x; printf(“%p”, p); printf(“%d”, *p); the data inside address p x=5 &x=FF00 p=address (FF00) &x x=5 address data

Sample Program : Pointers 1 /* Filename: Pointers.c Program Description: Pointer example */ Predict the output: 2 3 4 5 6 7 8 9 10 11 12 #include<stdio.h> main() { int count, value; int *count_address; count = 100; count_address=&count; value= *count_address; printf(“\n %p”, count_address); printf(“\n %d”, value); getch(); } 13 14 15 16 17 18 19 20

Review: Parameter Passing Two Ways: Pass by Value Pass by Reference

Review: Pass by Value int cubeByValue( int ); main() { int n = 5; printf(“Original value: %d”, n); n = cubeByValue( n ); printf(“\nNew value: %d”, n); getch(); ) int cubeByValue( int n ) { return n * n * n; }

Example 1: Pass by Reference int cubeByReference( int * ); main() { int n = 5; printf(“Original value: %d”, n); n = cubeByReference( &n ); printf(“\nNew value: %d”, n); getch(); ) int cubeByReference( int *nPtr ) { *nPtr = *nPtr * *nPtr * *nPtr; return *nPtr; }

Example 2: Pass by Reference void cubeByReference( int * ); main() { int n = 5; printf(“Original value: %d”, n); cubeByReference( &n ); printf(“\nNew value: %d”, n); getch(); } void cubeByReference( int *nPtr ) { *nPtr = *nPtr * *nPtr * *nPtr; }

Exercise: Create a function that would swap two numbers. The numbers must be pass as parameters of that function: Using pass by value Using pass by reference

Pointer Arithmetic Pointers only have limited set of operations: A pointer could be incremented (++) and decremented (--) An integer may be added (+, +=) to a pointer An integer may be subtracted (-, -=) from a pointer One pointer may be subtracted from another

Pointer Arithmetic int v[5]; vPtr can be initialized by: vPtr = v; vPtr = &v[0]; The diagram considers a machine (computer) with 4-byte integers. 5 9 8 7 6 v[0] v[1] v[2] v[3] v[4] 3000 3004 3008 3012 3016 3000 vPtr

Pointer Arithmetic Example: vPtr += 2; Result: 3000 + 2 * 4 = 3008 5 9 7 6 v[0] v[1] v[2] v[3] v[4] 3000 3004 3008 3012 3016 3000 vPtr 3008 vPtr

Pointer Arithmetic For arrays of other data types, vPtr would be incremented by twice the number of bytes that it takes to store an object of that data type. Example: char v[5]; vPtr += 2; Result: 3000 + 2 * 1 = 3002 ‘5’ ‘9’ ‘8’ ‘7’ ‘6’ v[0] v[1] v[2] v[3] v[4] 3000 3001 3002 3003 3004 3000 vPtr 3002 vPtr

Pointer Arithmetic Same case of a 2-byte integer machine. Example: int v[5]; vPtr += 2; Result: 3000 + 2 * 2 = 3004 Most computers have 2-byte or 4-byte integers. Some newer ones uses 8-byte machines. Because of this, pointer arithmetic is machine-dependent. ‘5’ ‘9’ ‘8’ ‘7’ ‘6’ v[0] v[1] v[2] v[3] v[4] 3000 3002 3004 3006 3008 3000 vPtr 3004 vPtr

Pointer Arithmetic If these are conducted in sequence: vPtr is incremented to 3016: vPtr += 4; vPtr is set back to address 3000: vPtr -= 4; To increment vPtr: ++vPtr; or vPtr++; To decrement vPtr: --vPtr; or vPtr--; 5 9 8 7 6 v[0] v[1] v[2] v[3] v[4] 3000 3004 3008 3012 3016 3000 vPtr

Pointer Arithmetic What would be the value of x? x = v2Ptr – vPtr; Pointer arithmetic is meaningless unless performed on an array. 5 9 8 7 6 v[0] v[1] v[2] v[3] v[4] 3000 3004 3008 3012 3016 3000 vPtr 3008 v2Ptr

Pointer Arithmetic Pointers can be compared using equality and relational operators, but is meaningless unless pointers point to members of the same array. Pointer comparisons compare the addresses stored in the pointers.

Generic Pointers A pointer can be assigned to another pointer if both pointers are of the same type. *a = *b; Otherwise, a cast operator must be used to convert the pointer. *a = * (int *) b;

Generic Pointers Exception: pointer to void (i.e. void *) Generic pointers can represent any pointer type. A cast operation is not required but we can cast any data variable as a pointer to void. A pointer to void cannot be dereferenced.

Example: Generic Pointers main() { int i; char c; void *v; clrscr(); i = 6; c = 'a'; v = &i; printf(“v points to %d\n", *(int *) v); v= &c; printf(“v now points to %c\n", *(char *) v); getch(); }

Pointer Arithmetic VALID: INVALID: Adding 2 pointers. Add an integer to a pointer. Subtract an integer from a pointer. Subtract 2 pointers (from the same array). Compare pointers (<, <=, ==, !=, >, >=). Compare pointer to NULL (indicates that pointer points to nothing). INVALID: Adding 2 pointers. Multiplying pointers. Dividing pointers. Subtracting a pointer from integer. Add or subtract type float or double to or from pointers.

Pointer Arithmetic Predict the output: int x[5] = { 1, 2, 3, 4, 5 }; printf(“\n %d”, *p1 ); int *p1; x[2] = *p1 + p1[2]; p1 = x; printf(“\n %d”, x[2] ); p1++;

Arrays and Pointers Arrays and pointers are closely related An array name is a constant pointer The name of the arrays points to the address/location of the first element of the array. Constant pointer means that it’s value (address/reference) could not be changed.

Arrays and Pointers Using ARRAY INDEXING: int v[5]; v 5 9 8 7 6 v[0] v[1] v[2] v[3] v[4] 3000 3002 3004 3006 3008 int v[5];

Arrays and Pointers Using POINTER MANIPULATION: int v[5]; int *p = v; Pointers can also be subscripted (indexed) exactly like arrays can. This is referred to as pointer/subscript notation. int v[5]; int *p = v; 5 9 8 7 6 p[0] p[1] p[2] p[3] p[4] 3000 3002 3004 3006 3008 3000 p

Arrays and Pointers Using POINTER MANIPULATION: int v[5]; int *p = v; Using pointer arithmetic, the array could be traversed. 5 9 8 7 6 p[0] p[1] p[2] p[3] p[4] 3000 3002 3004 3006 3008 3000 p int v[5]; int *p = v; p++; p += 3; *p--;

Passing Arrays using Pointers Sample Program : Passing Array Using Pointer 1 /* Filename: ArrayPtr.c Program Description: Display the string character by character */ Predict the output: 2 3 4 5 6 7 8 9 10 11 12 #include<stdio.h> void Display(char *p); main() { char str[6] = “hello”; Display( str ); getch(); } void Display( char *p ) while( *p ) putchar( *p ); p++; 13 14 15 16 17 18 19 20

Double Pointers A pointer whose value is the address of another pointer. Also called as a Pointers to pointers (i.e. pointers to int, pointers to char, etc.) Syntax: int **ptr; char **a;

Double Pointers Example: int **ipp; int i = 5, j = 6; k = 7; int *ip1 = &i, *ip2 = &j; ipp = &ip1; 7 5 6 i j k 3000 … 4FF1 … … 581C 123D ipp 3000 ip1 4FF1 ip2 54EA POINTER VALUES: *ipp = 3000 **ipp = 5

Double Pointers Example: *ipp = ip2; 7 5 6 i j k 3000 … 4FF1 … … 581C 54EA POINTER VALUES: *ipp = 4FF1 **ipp = 6

Double Pointers Example: *ipp = &k; 581C ip1 123D 7 5 6 i j k 3000 … 4FF1 … … 581C 123D ipp 4FF1 ip2 54EA POINTER VALUES: *ipp = 581C **ipp = 7

Dynamic Memory Allocation Allows to programmers to allocate (reserve) memory dynamically. Obtain more memory space at execution time. Common Library functions associated: malloc() free() sizeof()

Dynamic Memory Allocation Sample Program : Dynamic Allocation /* Filename: Dynamic.c Program Description: Using malloc */ Output: 5 10 20 30 40 #include<stdio.h> main() { int *p1,x; int *p[4]; p1=(int *) malloc(sizeof(int)); *p1= 5; printf(“\n%d”, *p1); p[0] = (int *) malloc( sizeof( int )); p[1] = (int *) malloc( sizeof ( int)); p[2] = (int *) malloc( sizeof( int )); p[3] = (int *) malloc( sizeof( int )); *p[0] = 10; *p[1] = 20; *p[2] = 30; *p[3] = 40; for(x=0; x<4; x++) printf(“\n%d”, *p[0] ); free( p[x] ); getch(); }

Pointers EXERCISE (By pairs): Make a function that accepts a pointer to a string and determine how many letter A’s are there in the string. Make a function that accepts an array of n integers and returns the average of these integers. Implement using pointers.

NOTES http://www.pcblab.net78.net/forum/ (PCBLab Forum > ComE Subjects > ComE 211)