Chapter 7 C Pointers

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

C Pointers Pearson Education, Inc. All rights reserved.

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

CSC 211 Intermediate Programming. Arrays & Pointers

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

C Pointers. 7.2 Pointer Variable Definitions and Initialization

Chapter 6 - Pointers

Lecture 05 POINTERS 1

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

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

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

MYcsvtu Notes LECTURE 34. POINTERS

today cs3157-fall2002-sklar-lect05 1

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

C++ Programming Chapter 7 Pointers

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

by Pearson Education, Inc. All Rights Reserved.

Chapter 5 - Pointers and Strings

Chapter 5 - Pointers and Strings

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

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

Arrays and Pointers. CSE 2031 Fall November 11, 2013

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

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

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

First of all, it is a variable, just like other variables you studied

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

SYSC 2006 C Winter 2012

Arrays and Pointers (part 1)

Arrays and Pointers (part 1)

CS113: Lecture 5. Topics: Pointers. Pointers and Activation Records

Language comparison. C has pointers. Java has references. C++ has pointers and references

Fundamentals of Programming. Lecture 11: C Characters and Strings

Sir Syed University of Engineering and Technology. Computer Programming & Problem Solving ( CPPS ) Pointers. Chapter No 7

Programming for Engineers Pointers

Fundamentals of Programming Session 20

BITG 1113: POINTER LECTURE 12

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

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.

DECLARAING AND INITIALIZING POINTERS

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

Objectives of This Chapter

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

CS3157: Advanced Programming. Outline

Using pointers with functions

Relationship between Pointers and Arrays

Pointers and Strings. Adhi Harmoko S, M.Komp

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

Chapter 8 - Characters and Strings

Pointers. Pointers. Pointers (cont) CS 217

Functions. Introduction :

[0569] p 0318 garbage

Computer Programming Lecture 12 Pointers

Converting a Lowercase Letter Character to Uppercase (Or Vice Versa)

Pointer in C SHARDA UNIVERSITY. Presented By: Pushpendra K. Rajput Assistant Professor

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

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

Tutorial 10 Pointers in C. Shuyue Hu

C++ for Java Programmers

Exercise 3 / Ch.7. Given the following array, write code to initialize all the elements to 0: int ed[100]; Hint: It can be done two different ways!

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

LESSON 4. The DATA TYPE char

Week 3: Pointers (Part 2)

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

PROGRAMMAZIONE I A.A. 2017/2018

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved.

Other C materials before pointer Common library functions [Appendix of K&R] 2D array, string manipulations. <stdlib.

Fundamentals of Programming Session 19

Content. In this chapter, you will learn:

Pointers. Pointer References

Procedural programming with C

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

Contents. Preface. Introduction. Introduction to C Programming

C: How to Program. Week /May/28

ECE 2400 Computer Systems Programming Fall 2017 Topic 4: C Pointers

Fundamentals of Programming Session 19

Fundamental of Programming (C)

CpSc 1011 Lab 11 Pointers

Variables, Pointers, and Arrays

Pointers as Arguments

Lecture 04 Introduction to pointers

Algorithms & Data Structures

Multidimension array, array of strings

Lab 3. Pointers Programming Lab (Using C) XU Silei

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Arrays, Pointers and Memory Management

Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

Pointers in C/C++ 1 Memory Addresses 2

Computer Organization & Systems Exam I Example Questions

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

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

Approximately a Test II CPSC 206

A Fast Review of C Essentials Part I

Pointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays

EM108 Software Development for Engineers

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

What is an algorithm?

Maltepe University Computer Engineering Department. BİL 133 Algoritma ve Programlama. Chapter 8: Arrays and pointers

C Arrays Pearson Education, Inc. All rights reserved.

Transcription:

Chapter 7 C Pointers

Objectives of This Chapter Definition and Operations with Pointers Using Pointers to pass arguments as call by reference call. Using Pointers to deal with arrays and strings. Character classification and conversion functions. Using Pointers to functions.

Introduction to Pointers Pointers are among the most powerful features of C Prog. Language. In particular, pointers are important for the following purposes: Simulating call by reference for a single variable. Sometimes, pointers make easier to deal with arrays. Dynamic Array allocations (the size of array may vary) (Chapter 12). Creating linked data structures (Chapter 12).

What is a Pointer? Pointers are the variables whose values are memory addresses. In other word, they point the memory address of regular variables that we have learned up to now. Memory Addresses: Every variable/elements of arrays defined in a program has a unique a memory addresses. & is the address operator. int avg; // Defining avg as integer type of variable (4byte space in the memory). &avg: memory address of variable avg in the memory. avg: value stored in this memory address. int exam[10]; // Defining int type exam array with 10 elements (4byte for each element). exam or &exam[0] : memory address of this array (actually the first one). For values of i: 0 <= i < 10: &exam[i]: the memory address of ith element of the array. exam[i]: value stored in this memory address. So far, we have only dealt with the values stored in the memory addresses, but now we will also learn how to deal with memory addresses with pointers.

Page 286 Pointers are just like all variables, must be defined in the program. While defining a pointer, we use an * (asterisk) in the front of the variable. Pointers have a type as like regular variables. Pointers points also their types of variables. Example: Defining a pointer and assigning a memory address to the pointer. int count, *countptr ; /*Defines int type of count and countptr pointer variable*/ count=7; countptr=&count; /*Assigning the memory address to countptr pointer*/ In the program above, count variable stores the 7 value. On the other hand, counptr points the memory address of count variable.

Page 287 Example: Reaching a variable directly and indirectly int count, *countptr ; count=7; countptr=&count; We can reach the value stored in count in two ways. 1) Using count variable name that directly referencing the value. printf( %d,count); 2) Using countptr pointer that indirectly referencing the value. printf( %d,*countptr); * operator in front of pointer commonly referred to as the indirection operator or dereferencing operator.

Example: Demonstrating Pointer Operators * and & Page 288 * What we have learned: &a and aptr are memory address of a. a and *aptr are value stored by a &* and *& are complements of each other. They both represents the memory address where the pointer points. * Output of Program *

Example: Use of Pointer * and & Operators Suppose that x and y are integer variables and ip is a pointer of integer type The program segment below shows how to declare a pointer and how to use & and * operators: Reminder about Arrays: As you may remember, the memory address of the first element in the array and the name of the array are same. So for arrays, you may use ptr = array_name ;

Page 289 There are two ways to pass arguments to a function (Chapter 5) Call by Value: Only value sent function can t change the variable. Sending only variable name is call by value Call by Reference: Memory address is sent, so function can change the variable defined in the main function. Sending array is call by reference (because name of array = memory address of the array). Functions can only return one value. In many programs, we may want to have functions capable of changing several variables. In this case, pointers can be used to simulate call by reference by sending the memory address of the variable instead of only sending the value.

Example: Cubing a Variable: Call By Value p. 290 Program cubes a variable by call by value. Conclusion, if we have only one variable to be modified, we can modify the variable by using the return value of the function.

Example: Cubing a Variable: Call By Reference p. 291 Program cubes a variable by call by reference.

Modifying Multiple Variables By Calling a Function if we have only one variable to be modified, we can modify the variable by using the return value of the function (Previous Call by Value Example). What if we have multiple variables their values needs to be changed within a function? In this case, we can do it only using call byreference. We can send the memory addresses of the variables to be modified then the function can directly modify the variable defined in the main program (calling one). Common example to this need is swapping the values of two variables. If we need to swap the values stored in two variables within a function, this can be done only using call by reference by sending the memory addresses of two variables.

Example: Function Swapping the values of two Variables Below code is an attempt to swap the values of two variables. /*WRONG*/ Main Program: Memory Allocation int a=5,b=7; swap(a, b); printf( a=%d b=%d,a,b); Function Swap: void swap(int x, int y) { int temp; temp = x; x = y; y = temp; } The program will print a=5 b=7, because a and b are passed to function as a call by value and only their values are sent. Function can t change the a and b defined in the main program.

Example: Function Swapping the values of two Variables Below code is an attempt to swap the values of two variables. Here we use a call by reference by passing the memory addresses of a and b. Main Program: int a=5,b=7; Memory Allocation swap(&a,&b); printf( a=%d b=%d,a,b); Function Swap: void swap(int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; } The program will print a=7 b=5, because a and b are passed to function as a call by reference, so the function can change the a and b variables using the memory addresses defined in the main program.

Example: Use of Pointer Operators & and * Swapping Program What will be the output of the following program? Main Program: int a=5,b=7,c=10; Int *px,*py; /*Defining a int type of two Pointers */ px=&a; /*px points the memory address of a */ *px+=3; py=&b; /*py points the memory address of b */ *py*=2; px=&c; /*px points the memory address of a */ *px = *px + *py + a + b + c; swap(px,py); /*Sending pointers px and py pointing a and b variables*/ swap(&a,&b); /*Sending Memory addresses of a and b variables.*/ printf( a=%d b=%d c=%d,a,b,c); Function Swap: void swap(int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; } The program will print a= b= c=. SEE 7.6 BUBBLE SORT USING CALL BY REFERENCE EXAMPLE GOOD EXAMPLE

Page 293 As we have learned, the const qualifier enables us to inform the compiler that the value of a particular variable should not be modified (defined as constant). So far, we have used const qualifiers for regular variables in two ways: 1) To define a variable whose value remains same and can t be changed. const int x=6; /*Defining x=6 and can t be changed through the program*/ 2) To not to allow function to change an array sent by caller. int linearsearch( const int array[], int key, int size ) int binarysearch( const int b[], int searchkey, int low, int high ); void printarray( const int a[], int size ); It is also possible to use const qualifiers to make a pointer constant or the value pointed constant throughout the program or function.

Page 293 Const qualifiers can be also used for pointers to limit the privileges of a function/program scope over the pointer and limit the privileges of the pointer over the data value. Remember: A pointer points a memory address + This memory stores a data So const qualifier can be used in three different ways. int *countptr; /*No Const. Qualifier Defined Nothing is constant*/ 1) const int *countptr=count; /*Non constant pointer to a Constant data*/ Pointer can be changed to point another address. Pointer can t be used to modify the data. 2) int * const countptr=count; /*Constant pointer to a Non Constant data*/ Pointer can t be changed and always points the same address address. Pointer can be used to modify the data. 3) const int * const countptr=count; /*Constant pointer to a Constant data*/ Pointer can t be changed and always points the same address address. Pointer can t be used to modify the data.

Page 297 Program given in Figure 7.12 illustrates the attempt to compile a function that receives a non constant pointer (xptr) to constant data. This function attempts to modify the data pointed to by xptr in line 20 which results in a compilation error. [Note: The actual error message you see will be compiler specific.]* Compilation Error Occurs:

Page 298 Program given in Figure 7.13 attempts to modify a constant pointer. Pointer ptr is defined in line 12 to be of type int * const. attempting a modify a constant pointer results in a compilation error. [Note: The actual error message you see will be compiler specific.]* Compilation Error Occurs:

Page 299 Program given in Figure 7.14 defines pointer variable ptr (line 13) to be of type const int *const, which is read from right to left as ptr is a constant pointer to an integer constant. This means, the pointer is constant and also the data in the pointed memory address is constant. The least access privilege given to pointer.* Compilation Error Occurs:

Pointer to Pointer In some programs, it is practical to define pointers that pointes another pointer. It is possible define such pointers to pointer by adding extra * in declaration statement. Example: In this example **pptr is used as pointer to pointer variable (Double Pointer).** Usage of multiple pointers in programming has many applications. In the scope of this course, this example is sufficient.

There is a strong relationship between pointers and arrays. Page 293 Any operation that can be achieved by arrays can be also done with pointers. The pointer version of such program will be in general faster but, the initialization is mostly not possible and somewhat harder to understand. In Chapter 6, (Example: Fig 6.12c Page 245) we have learned that Array name refers to the memory address of the first element in the array. (Output as shown below). In order to process such array, we can first define a pointer with the same type then set our pointer to point the first element. Assume, above array is int type, below shows how to set the pointer to an array: int *parray; /*Defining Pointer*/ parray = array ; or parray = &array[0] ; /*parray points the first element in the array*/

Pointers and Arrays Assume that an int type of array of size 10 is defined: int a[10]; /*This creates array of 10 elements shown as below*/ Now, we can define int type of pointer (pa) pointing the first element int *pa; /*Defining pa as int type of pointer*/ pa = a; or pa=&a[0]; /*Setting pointer to point the &a[0] */ pa gives the memory address of a[0] *pa gives the value of a[0] Now we can shift out pointer to i th element by increasing pa += i; as shown below: (This is known as pointer/offset notation) *pa gives the value of a[0] *(pa+1) gives the value of a[1]. *(pa+i) gives the value of a[i]

More on Pointers and Arrays We can deal with arrays by using pointer arithmetic by pa + i to shift the pointer from one to another element in the array (pa++, pa, pa, pa+=3, possible). int a[10]; /*This creates array of 10 elements shown as below*/ int *pa; /*Defining pa as int type of pointer*/ pa = a; or pa=&a[0]; /*Setting pointer to point the &a[0] */ Usually, we shift our pointer by pa+=i (pa=pa+i) to i th element. But if the pointer is constant pointer this will give a Error in Compilation. Furthermore, pointers can be subscripted as arrays can. pa[0] gives the a[0] value... pa[i] gives the a[i] value. pa gives the memory address of a[0] *pa gives the value of a[0]. pa+i gives the memory address of a[i] *(pa+i) gives the value of a[i] This is called array pointer subscript notation.

Example: Using Subscripting and pointer notations with arrays. #include <stdio.h> void main( void ){ int b[] = { 10, 20, 30, 40 }; /* initialize array b size of 4 */ int *bptr = b; /* set bptr to point to array b */ int i; /* counter */ /* output array b using array subscript notation */ printf( "Array b printed with:\narray subscript notation\n" ); /* loop through array b */ for ( i = 0; i < 4; i++ ) printf( "b[ %d ] = %d\n", i, b[i]); /* output array b using array name and pointer notation */ printf( "\npointer notation where\n" "the pointer is the array name\n" ); /* loop through array b */ for ( i = 0; i < 4; i++ )printf( "*( b + %d ) = %d\n", i, *( b + i ) ); /* output array b using bptr and array subscript notation */ printf( "\npointer subscript notation\n" ); /* loop through array b */ for ( i = 0; i < 4; i++ ) printf( "bptr[ %d ] = %d\n", i, bptr[i]); /* output array b using bptr and pointer/offset notation */ printf( "\npointer/offset notation\n" ); /* loop through array b */ for ( i = 0; i < 4; i++ ) printf( "*( bptr + %d ) = %d\n", i, *(bptr + i ) ); } /* end main */ Page 309 * Output of the Program *

Example: Converting a String to Uppercase Using A string is combined of characters. Therefore, we will check each character in the string if it is lowercase, if so convert it to uppercase using character manipulation functions. What we need to know? ctype.h: Library file declares set of character handling functions including classification and transformation of individual characters, some of which listed below.* Page 295 Character Classification Functions They check whether the character belongs to a certain category isblank: iscntrl: isdigit: islower: isspace: isupper: isxdigit: Check if character is blank Check if character is a control character Check if character is decimal digit Check if character is lowercase letter Check if character is a white-space Check if character is uppercase letter Check if character is hexadecimal digit and many more available under ctype.h Character conversion functions Two functions that convert between letter cases: tolower: Convert uppercase letter to lowercase toupper: Convert lowercase letter to uppercase Function Details: If the check test is true return value of this functions are nonzero, if false return value is zero. In this program we will only use islower toupper

Example: Converting a String to Uppercase Using a Non Constant Pointer to Non Constant Data.* Page 295 * Output of the Program *

Example: Printing a String One Character at a time Using a Non Constant Pointer to Constant Data.* Page 296 * Output of the Program *

Example: Swapping two Strings Below program demonstrates an attempt to swap two strings. ** Page 296 * Compilation Error * Conclusion: It is not that easy to copy strings, as like copying two regular variables. A string is an array itself, so copying must be done within a repetition for each elements.

Example: Copying a String Using Page 310 Below code copies a string to another string using array notation and pointer notation* * Output of the Program *

Special unary operator sizeof can be used to determine the size of any data variable or array in a program. Usage: sizeof object_name / sizeof ( type_name ) gives size in bytes.** * Output of the Program * Page 302

Example: Using sizeof to determine the size of an array Write a program that determines the size of an array. In your program define the array of int type as array[]={8,25,45,65,30,27}. Your program should determine the size internally using sizeof operator then print the size and the elements below it in rows. Hint: You may calculate the size of the array in the memory and divide it by the size of an individual element.]

Example: Using Pointer to Determine the Length of a String The functions named strlen_array determine the length of a string using arrays.**** or 1) Rewrite the same function by using pointers with the concept of pointer notation. or 2) Rewrite the same function that process the pointer as array subscript notation instead of pointer notation. or

Page 332

Page 331 * ANSWER: Adds the Second String to end of First String If Entered Grade Okay It will make the string 1 as GradeOkay

Page 333 * ANSWER: The program compares two strings, element by element, for equality. If they are same Returns 1 If they differ Returns 0

Pointers can also be defined as arrays called arrays of pointers. Commonly usage of array of pointers is to form an array of strings. similar to char name[5][30]; One may also define such array of strings using pointers see below Page 312 In this statement; Four character pointers to a constant values are defined. Each pointer points the first character of the strings given in the list. Graphical representation of suit array of pointer is shown below This could have been accomplished by defining char suit[4][max_size]. But this would be very memory consuming. Instead using pointers only points the first character of the string is more efficient in processing large amount of data. This flexibility is one example of C s powerful data structuring capabilities.

Pointers can also be defined to point functions. Page 317 A pointer to point a function can be defined as following; type (*pointer_name) (arguments); Type of the pointer should be same as the return value of the function Arguments of the function should be same as arguments of the function. Example: Let s consider a function int lookup (void); we can declare a pointer named fptr to point this function as the following int (*fptr) (void); Assigning pointer to a function is done similar to arrays: fptr=lookup; /*Now the pointer points the function*/ Function can be now indirectly called by using the pointer: result=fptr(); OR result=(*fptr)() /*Calls the function*/ Two Common Application of Pointers to Functions: Passing a function as argument to another function (revised bubble sort example). Creating dispatch table. Storing several functions in a pointer array and call them using the subscripting.

Example: Using Pointers to Point Functions Below example demonstrates to call a function indirectly by using pointers to functions.* * Output of the Program *

Example: Passing a Function to another Function as Argument Below example demonstrates to pass a function name to another function as argument. * * Output of the Program *

Multipurpose Bubble Sort using Function Pointers Page 317

Using Function Pointers to Create a Menu Driven System Page 321 Array of pointers can be used to point set of functions, so that each function can be invoked using the subscript of the array. Commonly used to make text based menu driven programs.* * Outputs: Choice:0 Choice:1 Choice:2