Module 9 Pointers.

Slides:



Advertisements
Similar presentations
C Language.
Advertisements

1 Chapter Thirteen Pointers. 2 Pointers A pointer is a sign used to point out the direction.
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.
Pointers in C Rohit Khokher
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Programming in C Pointers and Arrays, malloc( ). 7/28/092 Dynamic memory In Java, objects are created on the heap using reference variables and the new.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Kernighan/Ritchie: Kelley/Pohl:
Programming Pointers. Variables in Memory x i c The compiler determines where variables are placed in memory This placement cannot.
Programming in C Pointer Basics.
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.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
CSC 2400 Computer Systems I Lecture 5 Pointers and Arrays.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
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 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
Pointers *, &, array similarities, functions, sizeof.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
+ Pointers. + Content Address of operator (&) Pointers Pointers and array.
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
Programming in C Arrays, Structs and Strings. 7/28/092 Arrays An array is a collection of individual data elements that is:An array is a collection of.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
Topic 5 Addresses, Pointers and Arrays. 2 Objectives (Textbook Chapter 14) You should be able to describe: Addresses and Pointers Pointer Operators Pointer.
1-d Arrays.
Computer Organization and Design Pointers, Arrays and Strings in C
User-Written Functions
Chapter 8 Arrays, Strings and Pointers
Chapter 7 Pointers and C-Strings
Computer Science 210 Computer Organization
CSE 220 – C Programming Pointers.
A bit of C programming Lecture 3 Uli Raich.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
CS1010 Programming Methodology
C Programming Tutorial – Part I
C programming language
INC 161 , CPE 100 Computer Programming
C Basics.
Arrays in C.
Programming Languages and Paradigms
Lecture 6 C++ Programming
Stack Lesson xx   This module shows you the basic elements of a type of linked list called a stack.
Pointers and Arrays Chapter 12
Computer Science 210 Computer Organization
Pointers and References
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Programming in C Pointer Basics.
Object Oriented Programming COP3330 / CGS5409
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
Programming in C Pointer Basics.
Programming in C Pointer Basics.
Pointers and Arrays Chapter 12
Chapter 16 Pointers and Arrays
C++ Pointers and Strings
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Suggested self-checks: Section 7.11 #1-11
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Chapter 9: Pointers and String
Programming in C Pointers and Arrays.
Programming in C Pointer Basics.
Arrays and Pointers CSE 2031 Fall May 2019.
Pointers and References
C++ Pointers and Strings
Arrays and Pointers CSE 2031 Fall July 2019.
Module 5 Working with Arrays
Module 13 Dynamic Memory.
Presentation transcript:

Module 9 Pointers

@Copyright UMBC Training Centers 2012 Pointer Basics In this lesson we will learn the basic syntax for declaring and using pointers Upon completion of this lesson, you will be able to Declare pointer variables Use pointer syntax to assign and dereference pointers Evaluate expressions that use pointers www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 What is a Pointer A pointer variable (or simply “pointer”) is a variable that contains the memory address (location) of another variable Powerful, but dangerous if not used with discipline The variable to which the pointer points is known as the “pointee” www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Why Pointers? Pointers… lead to compact and efficient code. facilitate sharing data between different parts of an application. make it possible to get dynamically allocated memory when your application is executing. make it easy to represent relationships among data items. www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Pointer Caution They are a powerful low-level device. Undisciplined use can be confusing and thus the source of subtle, hard-to-find bugs. Program crashes Memory leaks Unpredictable results www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Declaring Pointers The general declaration of a pointer is type *nameOfPointer; For example int *pInt; www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Pointer Operators The & operator gives the address of a variable pInt = &age; assigns the address of age to the pointer pInt, and we say that pInt “points to” age; The * operator uses the pointer to access the pointee x = *pInt; assigns the value in the variable to which pInt points (the pointee) to x, and we say that we are “dereferencing” the pointer. www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Pointers in Memory int myAge, yourAge, *pAge; myAge = 42; pAge = &myAge; yourAge = *pAge + 3; www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 More Pointer Code int *ip = NULL, x = 1, y = 2; int z[3] = {0}; ip = &x; y = *ip; *ip = 0; *ip = *ip + 10; ip = &y; printf( “%d”, *ip); scanf(“%d”, ip); ip = &z[2]; *ip = x + y; www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Let’s take a look C::B – pointer1 Show 1st half of the code, have students predict the output Trace the code on board, then run the code Do the same with 2nd half of code www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Broken swap( ) void swap (int a, int b) { int temp = a; a = b; b = temp; } int main( ) { int x = 42, y = 77; swap(x, y); printf(“x = %d, y = %d\n”, x, y); www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Exercises pointers2 – students trace code and predict output Pg 277 #10 – rewriting char array code to use char* www.umbctraining.com @Copyright UMBC Training Centers 2012

Initialized Strings Revisited As an array of chars char name1[ ] = “Jimmy”; Using a CHAR pointer char *name2 = “Jimmy”; www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 String Parameters void printString1( char[ ] string) { printf(“%s\n”, string); } void printString2( char* string ) … printManyStrings( char* strings[], int count) for(int s = 0; s < count; s++) printf(“%s\n”, strings[s]); www.umbctraining.com @Copyright UMBC Training Centers 2012

Initialized Array of Strings char* names[3] = { “Bobby”, “Jim”, “Mary” }; printf (“My name is %s\n”, names[1]); www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Let’s take a look C::B – copyString (From the text; we would write this using while loop) Explain the array of char version General array copying algorithm Must append NUL char to end of “to” to make it a C-String Reveal and explain the pointer version www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 End of Day 1 Exercises Pg 276 #1 (11.1, - 11.3) #10 – Rewrite compareStrings from Ch10 using pointers #12 – printf with strings; predict first Ex5-DateStrings – create and use arrays of strings www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Pointer Parameters Pointer parameters allow us to simulate passing arguments “by reference” Argument is a pointer to a variable Parameter is a copy of the pointer Allows a function to alter the argument from within the function www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 swap( ) /* swap the values of pointees */ void swap (int *ip1, int *ip2) { int temp = *ip1; *ip1 = *ip2; *ip2 = temp; } int main() int x = 42, y = 77; int *ptrToX, *ptrToY; ptrToX = &x; ptrToY = &y; swap( ptrToX, ptrToY ); return 0; www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Let’s take a look C::B PointersAndFunction1 www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 “Output” Parameters void convertTime (int time, int *pHours, int *pMins) { *pHours = time / 60; *pMins = time % 60; } int main( ) int time, hours, minutes; printf("Enter a time duration in minutes: "); scanf ("%d", &time); convertTime (time, &hours, &minutes); printf("HH:MM format: %02d:%02d\n", hours, minutes); return 0; www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 An Exercise void myFunction (int a, int *b) { a = 7 ; // line 1 *b = a ; // line 2 b = &a ; // line 3 *b = 4 ; // line 4 printf("%d, %d\n", a, *b) ; // line 5 } int main() int m = 3, n = 5; // line 6 myFunction(m, &n) ; // line 7 printf("%d, %d\n", m, n) ; // line 8 return 0; www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Pointer to Structure typedef struct point { int x, y; } POINT; POINT center = {5, 10}; // structure initialization POINT corner = {3, 9}; POINT *pPoint; pPoint = &center; printf(“Center at (%d, %d)\n”, pPoint->x, pPoint->y); pPoint = &corner; printf(“Corner at (%d, %d)\n”, pPoint->x, pPoint->y); // less common but equivalent printf(“Center at (%d, %d)\n”, (*pPoint).x, (*pPoint.y)); www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Let’s take a look C::B – nap (name, address, person) Lot of functions with pointer to struct as parameters Start discussion with NAME, then ADDRESS, then finally PERSON www.umbctraining.com @Copyright UMBC Training Centers 2012

Pointer to struct parameter void inputPoint( struct point *pPoint) { printf(“Please input point coordinates: ”); scan(“%d %d”, &(pPoint->x), &(pPoint->y)); } void printPoint( struct point *pPoint) printf(“(%d, %d)”, pPoint->x, pPoint->y); int main( ) struct point center; inputPoint( &center ); printPoint( &center ); return 0; www.umbctraining.com @Copyright UMBC Training Centers 2012

Structures Containing Pointers struct intPtrs { int *p1, *p2; }; struct intPtrs bob; int int1 = 100, int2; bob.p1 = &int1; bob.p2 = &int2; *bob.p2 = -97; www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 NULL NULL is a predefined special value for pointers Points to “nothing” Some programmers like to initialize all pointers to NULL when they are defined double *pRatio = NULL; Program termination if we dereference a pointer that is NULL www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Exercises Text, #1 pg 275 Ex1-Coins2 – nr coins from N cents (pointer parameters) Ex2-Division Ex3-Money – pointer to struct as function parameter Ex4 – People – struct parameters/return values www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 End of Day 1?? www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Pointers and Arrays Arrays are commonly used to store data In C, there is an intimate relationship between pointers and arrays www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Basics int a[4] = {11, 13, 15, 17}; int *ip, x; ip = &a[0]; x = *ip; x = *(ip + 1); x = *(ip + 2); www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 The Big Ideas If ip points to a[0], then ip + i points to a[i] and *(ip + i) is synonymous with a[i] More generally, ip + i points i elements beyond where ip is pointing The statement ip = ip + i; moves ip to point i elements beyond where it currently points www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 More Big Ideas Since the name of an array is synonymous with the address of (pointer to) its first element… The name of an array can be thought of as a pointer to the first element of the array and vice-versa ip = a; is equivalent to ip = &a[0]; *(ip + i), *(a + i) and ip[i] are all equivalent to a[i] www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Let’s take a look CB – PointersAndArrays1 typical code and you should use [ ] with arrays – clearer going to see array code that uses pointers instead it’s important that we examine the different ways to write this code First create a new pointer variable and change the code in the for-loop to use pointer arithmetic ADD int *pWeight = &weights[ 0 ] ; change weights[i] to *(pWeight+i) As the for-loop changes the value of I, pWeight+I iterates through the elements of the array, just like before To show that “weights” acts like a pointer, change pWeight to “weights” www.umbctraining.com @Copyright UMBC Training Centers 2012

Arrays and Functions Revisited Array name is a pointer to its first element Array parameter could be replaced with a pointer parameter Compiler treats array parameters as pointers Reflected in error messages Use an array parameter if the function uses an index to access the members of an array www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Let’s take a look CB -- PointersAndArrays2 change array parameter to a[300] to illustrate that parameter is just the address of where the array is located in memory… a “pointer” change array parameter to pointer parameter change code to *(a + i) Error messages related to the array parameter will use pointer terminology Change int a[] to float a[] and look at the log www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 What’s the difference? Between an array and a pointer variable A pointer is a variable that can point to different variables during execution Array name is NOT a variable and can only “point to” its first element Now we know why scanf does not require & for %s arguments www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Let’s take a look C::B - ConstPointers CB: PtrExpressions – hand out table to be completed by students C::B CompareStrings Modify to use pointer+offset www.umbctraining.com @Copyright UMBC Training Centers 2012

Initialized Strings Revisited As an array of chars char name1[ ] = “Jimmy”; Using a pointer char *name2 = “Jimmy”; www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Let’s take a look C::B – copyString Explain the array of char version General array copying algorithm Must append NUL char to end of “to” to make it a C-String Reveal and explain the pointer version www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Array of Strings char *names[3] = { “Bobby”, “Jim”}; names[2] = “Mary”; printf (“My name is %s\n”, names[1]); www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 String Parameters printString1( char string[] ) { printf(“%s\n”, string); } printString2( char *string ) printManyStrings( char *strings[ ], int count) for(int s = 0; s < count; s++) printf(“%s\n”, strings[s]); www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 More String Functions char *strchr(char * string, char c) returns a pointer to the first occurrence of c in string or NULL if not found char *strpbrk(char *s1, char *s2) returns a pointer to the first occurrence of any character in s2 found in s1 or NULL if not found char *strrchr(char * string, char c) returns a pointer to the last occurrence of c in string or NULL if not found char* strstr(char *s1, char *s2) returns a pointer to the first occurrence of s2 in s1 or NULL if not found www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Let’s take a look C::B – String Functions Add code after strchr() to find the next ‘w’ add code after strchr( ) call to print index where ‘w’ is found by showing pointer subtraction www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Exercises PtrExpressions.docx experimenting with ++*p, etc Ex4-DateStrings www.umbctraining.com @Copyright UMBC Training Centers 2012

More Pointer Operations To access array elements and traverse through the array use *arrayPtr++ Dereferences arrayPtr,then increments it void copyString( char *to, char *from ) { while (*from) *to++ = *from++; *to = ‘\0’; } www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Let’s take a look Ex3-PointerExpression www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Exercises Text #8 – function to sort 3 integers with pointer params (not array) #12 Ex2-ExchangeSort (same as Ex7) Ex5-DateStrings Ex6 – Gymnastic Scores – array as function parameters Ex7-Gettysburg – string functions that return pointer www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 If you have any comments about this video, please use the contact information in your registration materials to let us know www.umbctraining.com @Copyright UMBC Training Centers 2012