Chapter 7 C Pointers

Size: px
Start display at page:

Download "Chapter 7 C Pointers"

Transcription

1 Chapter 7 C Pointers

2 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.

3 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).

4 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.

5 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.

6 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.

7 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 *

8 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 ;

9 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.

10 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.

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

12 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.

13 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.

14 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.

15 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

16 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.

17 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.

18 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:

19 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:

20 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:

21 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.

22 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*/

23 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]

24 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.

25 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 *

26 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

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

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

29 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.

30 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 *

31 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

32 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.]

33 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

34 Page 332

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

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

37 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.

38 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.

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

40 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 *

41 Multipurpose Bubble Sort using Function Pointers Page 317

42 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

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

Chapter 7. Pointers. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 7 Pointers Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 2 Chapter 7 - Pointers 7.1 Introduction 7.2 Pointer Variable Definitions and Initialization

More information

C Pointers Pearson Education, Inc. All rights reserved.

C Pointers Pearson Education, Inc. All rights reserved. 1 7 C Pointers 2 Addresses are given to us to conceal our whereabouts. Saki (H. H. Munro) By indirection find direction out. William Shakespeare Many things, having full reference To one consent, may work

More information

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

C Pointers. Indirection Indirection = referencing a value through a pointer. Creating Pointers. Pointer Declarations. Pointer Declarations 55:017, Computers in Engineering C Pointers C Pointers Powerful C feature but challenging to understand Some uses of pointers include Call by reference parameter passage Dynamic data structures Data structures

More information

CSC 211 Intermediate Programming. Arrays & Pointers

CSC 211 Intermediate Programming. Arrays & Pointers CSC 211 Intermediate Programming Arrays & Pointers 1 Definition An array a consecutive group of memory locations that all have the same name and the same type. To create an array we use a declaration statement.

More information

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

COMP26120: Pointers in C (2018/19) Lucas Cordeiro COMP26120: Pointers in C (2018/19) Lucas Cordeiro lucas.cordeiro@manchester.ac.uk Organisation Lucas Cordeiro (Senior Lecturer, FM Group) lucas.cordeiro@manchester.ac.uk Office: 2.44 Office hours: 10-11

More information

C Pointers. 7.2 Pointer Variable Definitions and Initialization

C Pointers. 7.2 Pointer Variable Definitions and Initialization 1 7 C Pointers 7.2 Pointer Variable Definitions and Initialization Pointer variables Contain memory addresses as their values Normal variables contain a specific value (direct reference) Pointers contain

More information

Chapter 6 - Pointers

Chapter 6 - Pointers Chapter 6 - Pointers Outline 1 Introduction 2 Pointer Variable Declarations and Initialization 3 Pointer Operators 4 Calling Functions by Reference 5 Using the const Qualifier with Pointers 6 Bubble Sort

More information

Lecture 05 POINTERS 1

Lecture 05 POINTERS 1 Lecture 05 POINTERS 1 Pointers Powerful, but difficult to master Simulate call-by-reference Close relationship with arrays and strings Pointer Variable vs. Normal Variable Normal variables contain a specific

More information

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

Pointers. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Pointers Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline 7.1 Introduction 7.2 Pointer Variable Definitions and Initialization 7.3 Pointer

More information

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

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 1 7 C Pointers 7.7 sizeof Operator 2 sizeof Returns size of operand in bytes For arrays: size of 1 element * number of elements if sizeof( int ) equals 4 bytes, then int myarray[ 10 ]; printf( "%d", sizeof(

More information

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

Pointers and Strings Prentice Hall, Inc. All rights reserved. Pointers and Strings 1 Introduction Pointer Variable Declarations and Initialization Pointer Operators Calling Functions by Reference Using const with Pointers Selection Sort Using Pass-by-Reference 2

More information

MYcsvtu Notes LECTURE 34. POINTERS

MYcsvtu Notes LECTURE 34.  POINTERS LECTURE 34 POINTERS Pointer Variable Declarations and Initialization Pointer variables Contain memory addresses as their values Normal variables contain a specific value (direct reference) Pointers contain

More information

today cs3157-fall2002-sklar-lect05 1

today cs3157-fall2002-sklar-lect05 1 today homework #1 due on monday sep 23, 6am some miscellaneous topics: logical operators random numbers character handling functions FILE I/O strings arrays pointers cs3157-fall2002-sklar-lect05 1 logical

More information

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

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples: 1 Programming in C Pointer Variable A variable that stores a memory address Allows C programs to simulate call-by-reference Allows a programmer to create and manipulate dynamic data structures Must be

More information

C++ Programming Chapter 7 Pointers

C++ Programming Chapter 7 Pointers C++ Programming Chapter 7 Pointers Yih-Peng Chiou Room 617, BL Building (02) 3366-3603 ypchiou@cc.ee.ntu.edu.tw Photonic Modeling and Design Lab. Graduate Institute of Photonics and Optoelectronics & Department

More information

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

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3). cs3157: another C lecture (mon-21-feb-2005) C pre-processor (1). today: C pre-processor command-line arguments more on data types and operators: booleans in C logical and bitwise operators type conversion

More information

by Pearson Education, Inc. All Rights Reserved.

by Pearson Education, Inc. All Rights Reserved. Let s improve the bubble sort program of Fig. 6.15 to use two functions bubblesort and swap. Function bubblesort sorts the array. It calls function swap (line 51) to exchange the array elements array[j]

More information

Chapter 5 - Pointers and Strings

Chapter 5 - Pointers and Strings Chapter 5 - Pointers and Strings 1 5.1 Introduction 2 5.1 Introduction 5.2 Pointer Variable Declarations and Initialization 5.3 Pointer Operators 5. Calling Functions by Reference 5.5 Using const with

More information

Chapter 5 - Pointers and Strings

Chapter 5 - Pointers and Strings Chapter 5 - Pointers and Strings 1 5.1 Introduction 5.2 Pointer Variable Declarations and Initialization 5.3 Pointer Operators 5.4 Calling Functions by Reference 5.5 Using const with Pointers 5.6 Bubble

More information

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

POINTERS. Content. Pointers. Benefits of Pointers. In this chapter, you will learn: Content POINTERS Erkut ERDEM Hacettepe University December 2010 In this chapter, you will learn: To be able to use pointers. To be able to use pointers to pass arguments to functions using call by reference.

More information

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

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8 Pointers Variables vs. Pointers: A variable in a program is something with a name and a value that can vary. The way the compiler and linker handles this is that it assigns a specific block of memory within

More information

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Arrays and Pointers. CSE 2031 Fall November 11, 2013 Arrays and Pointers CSE 2031 Fall 2013 November 11, 2013 1 Arrays l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. 2 Arrays: Example

More information

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

Outline. Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary Pointers 1 2 Outline Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary 3 Computer Memory Revisited Computers store data in memory slots Each slot has an

More information

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types Programming Fundamentals for Engineers 0702113 5. Basic Data Types Muntaser Abulafi Yacoub Sabatin Omar Qaraeen 1 2 C Data Types Variable definition C has a concept of 'data types' which are used to define

More information

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

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014. Arrays Arrays and Pointers l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. EECS 2031 Fall 2014 November 11, 2013 1 2 Arrays: Example

More information

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

Pointers and Strings Prentice Hall, Inc. All rights reserved. Pointers and Strings 1 sizeof operator Pointer Expressions and Pointer Arithmetic Relationship Between Pointers and Arrays Arrays of Pointers Case Study: Card Shuffling and Dealing Simulation sizeof operator

More information

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

First of all, it is a variable, just like other variables you studied Pointers: Basics 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 address (rather than the value)

More information

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

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017 Pointers (part 1) EECS 2031 25 September 2017 1 What are pointers? We have seen pointers before. scanf( %f, &inches );! 2 1 Example char c; c = getchar(); printf( %c, c); char c; char *p; c = getchar();

More information

SYSC 2006 C Winter 2012

SYSC 2006 C Winter 2012 SYSC 2006 C Winter 2012 Pointers and Arrays Copyright D. Bailey, Systems and Computer Engineering, Carleton University updated Sept. 21, 2011, Oct.18, 2011,Oct. 28, 2011, Feb. 25, 2011 Memory Organization

More information

Arrays and Pointers (part 1)

Arrays and Pointers (part 1) Arrays and Pointers (part 1) CSE 2031 Fall 2010 17 October 2010 1 Arrays Grouping of data of the same type. Loops commonly used for manipulation. Programmers set array sizes explicitly. 2 1 Arrays: Example

More information

Arrays and Pointers (part 1)

Arrays and Pointers (part 1) Arrays and Pointers (part 1) CSE 2031 Fall 2012 Arrays Grouping of data of the same type. Loops commonly used for manipulation. Programmers set array sizes explicitly. Arrays: Example Syntax type name[size];

More information

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

CS113: Lecture 5. Topics: Pointers. Pointers and Activation Records CS113: Lecture 5 Topics: Pointers Pointers and Activation Records 1 From Last Time: A Useless Function #include void get_age( int age ); int age; get_age( age ); printf( "Your age is: %d\n",

More information

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

Language comparison. C has pointers. Java has references. C++ has pointers and references Pointers CSE 2451 Language comparison C has pointers Java has references C++ has pointers and references Pointers Values of variables are stored in memory, at a particular location A location is identified

More information

Fundamentals of Programming. Lecture 11: C Characters and Strings

Fundamentals of Programming. Lecture 11: C Characters and Strings 1 Fundamentals of Programming Lecture 11: C Characters and Strings Instructor: Fatemeh Zamani f_zamani@ce.sharif.edu Sharif University of Technology Computer Engineering Department The lectures of this

More information

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

Sir Syed University of Engineering and Technology. Computer Programming & Problem Solving ( CPPS ) Pointers. Chapter No 7 Computer Programming & Problem Solving ( CPPS ) Chapter No 7 Sir Syed University of Engineering & Technology Computer Engineering Department University Road, Karachi-75300, PAKISTAN Muzammil Ahmad Khan

More information

Programming for Engineers Pointers

Programming for Engineers Pointers Programming for Engineers Pointers ICEN 200 Spring 2018 Prof. Dola Saha 1 Pointers Pointers are variables whose values are memory addresses. A variable name directly references a value, and a pointer indirectly

More information

Fundamentals of Programming Session 20

Fundamentals of Programming Session 20 Fundamentals of Programming Session 20 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

BITG 1113: POINTER LECTURE 12

BITG 1113: POINTER LECTURE 12 BITG 1113: POINTER LECTURE 12 1 LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the concept of pointer. 2. Write declaration and initialization of a pointer. 3. Do arithmetic

More information

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

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21 Department of Computer Science College of Engineering Boise State University September 11, 2017 1/21 Pointers A pointer is a variable that stores the address of another variable. Pointers are similar to

More information

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.

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. Chapter 9: Pointers 9.1 Getting the Address of a Variable C++ Variables [ not in book ] A Variable has all of the following attributes: 1. name 2. type 3. size 4. value 5. storage class static or automatic

More information

DECLARAING AND INITIALIZING POINTERS

DECLARAING AND INITIALIZING POINTERS DECLARAING AND INITIALIZING POINTERS Passing arguments Call by Address Introduction to Pointers Within the computer s memory, every stored data item occupies one or more contiguous memory cells (i.e.,

More information

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

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 ARRAYS ~ VECTORS KOM3191 Object-Oriented Computer Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2 What is an array? Arrays

More information

Objectives of This Chapter

Objectives of This Chapter Chapter 6 C Arrays Objectives of This Chapter Array data structures to represent the set of values. Defining and initializing arrays. Defining symbolic constant in a program. Using arrays to store, list,

More information

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

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018 Pointer Basics Lecture 13 COP 3014 Spring 2018 March 28, 2018 What is a Pointer? A pointer is a variable that stores a memory address. Pointers are used to store the addresses of other variables or memory

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #8 Feb 27 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline More c Preprocessor Bitwise operations Character handling Math/random Review for midterm Reading: k&r ch

More information

Using pointers with functions

Using pointers with functions Using pointers with functions Recall that our basic use of functions so fare provides for several possibilities. A function can 1. take one or more individual variables as inputs and return a single variable

More information

Relationship between Pointers and Arrays

Relationship between Pointers and Arrays Relationship between Pointers and Arrays Arrays and pointers are intimately related in C and often may be used interchangeably. An array name can be thought of as a constant pointer. Pointers can be used

More information

Pointers and Strings. Adhi Harmoko S, M.Komp

Pointers and Strings. Adhi Harmoko S, M.Komp Pointers and Strings Adhi Harmoko S, M.Komp Introduction Pointers Powerful, but difficult to master Simulate call-by-reference Close relationship with arrays and strings Pointer Variable Declarations and

More information

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

Pointers and Structure. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island Pointers and Structure Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island 1 Pointer Variables Each variable in a C program occupies space in

More information

Chapter 8 - Characters and Strings

Chapter 8 - Characters and Strings 1 Chapter 8 - Characters and Strings Outline 8.1 Introduction 8.2 Fundamentals of Strings and Characters 8.3 Character Handling Library 8.4 String Conversion Functions 8.5 Standard Input/Output Library

More information

Pointers. Pointers. Pointers (cont) CS 217

Pointers. Pointers. Pointers (cont) CS 217 Pointers CS 217 Pointers Variables whose values are the addresses of variables Operations address of (reference) & indirection (dereference) * arithmetic +, - Declaration mimics use char *p; *p is a char,

More information

Functions. Introduction :

Functions. Introduction : Functions Introduction : To develop a large program effectively, it is divided into smaller pieces or modules called as functions. A function is defined by one or more statements to perform a task. In

More information

[0569] p 0318 garbage

[0569] p 0318 garbage A Pointer is a variable which contains the address of another variable. Declaration syntax: Pointer_type *pointer_name; This declaration will create a pointer of the pointer_name which will point to the

More information

Computer Programming Lecture 12 Pointers

Computer Programming Lecture 12 Pointers Computer Programming Lecture 2 Pointers Assist.Prof.Dr. Nükhet ÖZBEK Ege University Department of Electrical & Electronics Engineering nukhet.ozbek@ege.edu.tr Topics Introduction to Pointers Pointers and

More information

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

Converting a Lowercase Letter Character to Uppercase (Or Vice Versa) Looping Forward Through the Characters of a C String A lot of C string algorithms require looping forward through all of the characters of the string. We can use a for loop to do that. The first character

More information

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

Pointer in C SHARDA UNIVERSITY. Presented By: Pushpendra K. Rajput Assistant Professor Pointer in C Presented By: Pushpendra K. Rajput Assistant Professor 1 Introduction The Pointer is a Variable which holds the Address of the other Variable in same memory. Such as Arrays, structures, and

More information

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

C Pointers. CS 2060 Week 6. Prof. Jonathan Ventura CS 2060 Week 6 1 Pointer Variables 2 Pass-by-reference 3 const pointers 4 Pointer arithmetic 5 sizeof 6 Arrays of pointers 7 Next Time Pointers The pointer is one of C s most powerful and important features.

More information

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

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University C Programming Notes Dr. Karne Towson University Reference for C http://www.cplusplus.com/reference/ Main Program #include main() printf( Hello ); Comments: /* comment */ //comment 1 Data Types

More information

Tutorial 10 Pointers in C. Shuyue Hu

Tutorial 10 Pointers in C. Shuyue Hu Tutorial 10 Pointers in C Shuyue Hu Content Basic concept of pointers Pointer arithmetic Array of pointers Pointer to pointer Passing pointers to functions in C Return pointer from functions in C 2 Content

More information

C++ for Java Programmers

C++ for Java Programmers Basics all Finished! Everything we have covered so far: Lecture 5 Operators Variables Arrays Null Terminated Strings Structs Functions 1 2 45 mins of pure fun Introduction Today: Pointers Pointers Even

More information

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!

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! 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! Exercise 3 / Ch.8 Given the following array, write code

More information

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

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables 1 6 C Arrays 6.2 Arrays 2 Array Group of consecutive memory locations Same name and type To refer to an element, specify Array name + position number arrayname[ position number ] First element at position

More information

LESSON 4. The DATA TYPE char

LESSON 4. The DATA TYPE char LESSON 4 This lesson introduces some of the basic ideas involved in character processing. The lesson discusses how characters are stored and manipulated by the C language, how characters can be treated

More information

Week 3: Pointers (Part 2)

Week 3: Pointers (Part 2) Advanced Programming (BETC 1353) Week 3: Pointers (Part 2) Dr. Abdul Kadir abdulkadir@utem.edu.my Learning Outcomes: Able to describe the concept of pointer expression and pointer arithmetic Able to explain

More information

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

Pointers in C. Recap: Anatomy of a Typical C Program. declarations variables functions. int main (void){ declarations; statements; return value; } Recap: Anatomy of a Typical C Program #preprocessor directives Pointers in C BBM 101 - Introduction to Programming I Hacettepe University Fall 2016 Fuat Akal, Aykut Erdem, Erkut Erdem declarations variables

More information

PROGRAMMAZIONE I A.A. 2017/2018

PROGRAMMAZIONE I A.A. 2017/2018 PROGRAMMAZIONE I A.A. 2017/2018 A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. DECLARING POINTERS POINTERS A pointer represents both

More information

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

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved. C How to Program, 7/e This chapter serves as an introduction to data structures. Arrays are data structures consisting of related data items of the same type. In Chapter 10, we discuss C s notion of

More information

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

Other C materials before pointer Common library functions [Appendix of K&R] 2D array, string manipulations. <stdlib. 1 The previous lecture Other C materials before pointer Common library functions [Appendix of K&R] 2D array, string manipulations Pointer basics 1 Common library functions [Appendix of K+R]

More information

Fundamentals of Programming Session 19

Fundamentals of Programming Session 19 Fundamentals of Programming Session 19 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Content. In this chapter, you will learn:

Content. In this chapter, you will learn: ARRAYS & HEAP Content In this chapter, you will learn: To introduce the array data structure To understand the use of arrays To understand how to define an array, initialize an array and refer to individual

More information

Pointers. Pointer References

Pointers. Pointer References Pointers Pointers are variables whose values are the addresses of other variables Basic operations address of (reference) indirection (dereference) Suppose x and y are integers, p is a pointer to an integer:

More information

Procedural programming with C

Procedural programming with C Procedural programming with C Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 77 Functions Similarly to its mathematical

More information

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

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty! Chapter 6 - Functions return type void or a valid data type ( int, double, char, etc) name parameter list void or a list of parameters separated by commas body return keyword required if function returns

More information

Contents. Preface. Introduction. Introduction to C Programming

Contents. Preface. Introduction. Introduction to C Programming c11fptoc.fm Page vii Saturday, March 23, 2013 4:15 PM Preface xv 1 Introduction 1 1.1 1.2 1.3 1.4 1.5 Introduction The C Programming Language C Standard Library C++ and Other C-Based Languages Typical

More information

C: How to Program. Week /May/28

C: How to Program. Week /May/28 C: How to Program Week 14 2007/May/28 1 Chapter 8 - Characters and Strings Outline 8.1 Introduction 8.2 Fundamentals of Strings and Characters 8.3 Character Handling Library 8.4 String Conversion Functions

More information

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

ECE 2400 Computer Systems Programming Fall 2017 Topic 4: C Pointers ECE 2400 Computer Systems Programming Fall 2017 Topic 4: C Pointers School of Electrical and Computer Engineering Cornell University revision: 2017-09-23-11-06 1 Pointer Basics 2 2 Call by Value vs. Call

More information

Fundamentals of Programming Session 19

Fundamentals of Programming Session 19 Fundamentals of Programming Session 19 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 9 Pointer Department of Computer Engineering 1/46 Outline Defining and using Pointers

More information

CpSc 1011 Lab 11 Pointers

CpSc 1011 Lab 11 Pointers CpSc 1011 Lab 11 Pointers Overview Pointers are an integral part of C and C++. While they may be the cause of many headaches, they allow for a great deal of control and flexibility. Because they are low-level

More information

Variables, Pointers, and Arrays

Variables, Pointers, and Arrays Variables, Pointers, and Arrays Prof. David August COS 217 http://www.cs.princeton.edu/courses/archive/fall06/cos217/ 1 Overview of Today s Lecture Pointers o Differences between value, variable, and pointer

More information

Pointers as Arguments

Pointers as Arguments Introduction as Arguments How it Works called program on start of execution xw = &i xf = &d after excution xw = &i xf = &d caller program i? d? i 3 d.14159 x 3.14159 x 3.14159 R. K. Ghosh (IIT-Kanpur)

More information

Lecture 04 Introduction to pointers

Lecture 04 Introduction to pointers Lecture 04 Introduction to pointers A pointer is an address in the memory. One of the unique advantages of using C is that it provides direct access to a memory location through its address. A variable

More information

Algorithms & Data Structures

Algorithms & Data Structures GATE- 2016-17 Postal Correspondence 1 Algorithms & Data Structures Computer Science & Information Technology (CS) 20 Rank under AIR 100 Postal Correspondence Examination Oriented Theory, Practice Set Key

More information

Multidimension array, array of strings

Multidimension array, array of strings 1 Multidimension array, array of strings char messages[3][7] ={ Hello, Hi, There ; Array of strings 0 1 2 0 1 2 3 4 5 6 H e l l o \0 H i \0 T h e r e \0 Each row (e.g., message[0]) is a char array (string)

More information

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

Lab 3. Pointers Programming Lab (Using C) XU Silei Lab 3. Pointers Programming Lab (Using C) XU Silei slxu@cse.cuhk.edu.hk Outline What is Pointer Memory Address & Pointers How to use Pointers Pointers Assignments Call-by-Value & Call-by-Address Functions

More information

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

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University Fundamental Data Types CSE 130: Introduction to Programming in C Stony Brook University Program Organization in C The C System C consists of several parts: The C language The preprocessor The compiler

More information

Arrays, Pointers and Memory Management

Arrays, Pointers and Memory Management Arrays, Pointers and Memory Management EECS 2031 Summer 2014 Przemyslaw Pawluk May 20, 2014 Answer to the question from last week strct->field Returns the value of field in the structure pointed to by

More information

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

Chapter 2 (Dynamic variable (i.e. pointer), Static variable) Chapter 2 (Dynamic variable (i.e. pointer), Static variable) August_04 A2. Identify and explain the error in the program below. [4] #include int *pptr; void fun1() { int num; num=25; pptr= &num;

More information

Pointers in C/C++ 1 Memory Addresses 2

Pointers in C/C++ 1 Memory Addresses 2 Pointers in C/C++ Contents 1 Memory Addresses 2 2 Pointers and Indirection 3 2.1 The & and * Operators.............................................. 4 2.2 A Comment on Types - Muy Importante!...................................

More information

Computer Organization & Systems Exam I Example Questions

Computer Organization & Systems Exam I Example Questions Computer Organization & Systems Exam I Example Questions 1. Pointer Question. Write a function char *circle(char *str) that receives a character pointer (which points to an array that is in standard C

More information

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

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ... Why Pointers Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation. They provide support for dynamic data structures, such

More information

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

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers and Arrays CS 201 This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers Powerful but difficult to master Used to simulate pass-by-reference

More information

Approximately a Test II CPSC 206

Approximately a Test II CPSC 206 Approximately a Test II CPSC 206 Sometime in history based on Kelly and Pohl Last name, First Name Last 5 digits of ID Write your section number(s): All parts of this exam are required unless plainly and

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

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

Pointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays EE105: Software Engineering II Part 6 Pointers page 1 of 19 Part VI Pointers 1) Introduction 2) Declaring Pointer Variables 3) Using Pointers 4) Pointer Arithmetic 5) Pointers and Arrays 6) Pointers and

More information

EM108 Software Development for Engineers

EM108 Software Development for Engineers EE108 Section 6 Pointers page 1 of 20 EM108 Software Development for Engineers Section 6 - Pointers 1) Introduction 2) Declaring Pointer Variables 3) Using Pointers 4) Pointer Arithmetic 5) Pointers and

More information

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

Outline. Introduction. Pointer variables. Pointer operators. Calling functions by reference. Using const with pointers. Examples. Outline Introduction. Pointer variables. Pointer operators. Calling functions by reference. Using const with pointers. Examples. 1 Introduction A pointer is a variable that contains a memory address Pointers

More information

What is an algorithm?

What is an algorithm? Announcements CS 142 C++ Pointers Reminder Program 6 due Sunday, Nov. 9 th by 11:55pm 11/3/2014 2 Pointers and the Address Operator Pointer Variables Each variable in a program is stored at a unique address

More information

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

Maltepe University Computer Engineering Department. BİL 133 Algoritma ve Programlama. Chapter 8: Arrays and pointers Maltepe University Computer Engineering Department BİL 133 Algoritma ve Programlama Chapter 8: Arrays and pointers Basics int * ptr1, * ptr2; int a[10]; ptr1 = &a[2]; ptr2 = a; // equivalent to ptr2 =

More information

C Arrays Pearson Education, Inc. All rights reserved.

C Arrays Pearson Education, Inc. All rights reserved. 1 6 C Arrays 2 Now go, write it before them in a table, and note it in a book. Isaiah 30:8 To go beyond is as wrong as to fall short. Confucius Begin at the beginning, and go on till you come to the end:

More information