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

Similar documents
by Pearson Education, Inc. All Rights Reserved.

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

C Pointers. 7.2 Pointer Variable Definitions and Initialization

C Pointers Pearson Education, Inc. All rights reserved.

Programming for Engineers Pointers

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

Lecture 05 POINTERS 1

C++ Programming Chapter 7 Pointers

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

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

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

Chapter 6 - Pointers

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

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

MYcsvtu Notes LECTURE 34. POINTERS

Fundamentals of Programming Session 19

Operating Systems 2INC0 C course Pointer Advanced. Dr. Ir. Ion Barosan

Fundamentals of Programming Session 19

Chapter 7 C Pointers

Fundamentals of Programming Session 20

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

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

Pointers and Strings. Adhi Harmoko S, M.Komp

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

Fundamentals of Programming Session 20

PROGRAMMAZIONE I A.A. 2017/2018

Fundamental of Programming (C)

CSC 211 Intermediate Programming. Arrays & Pointers

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

A Fast Review of C Essentials Part I

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

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

C++ for Java Programmers

Administrivia. Introduction to Computer Systems. Pointers, cont. Pointer example, again POINTERS. Project 2 posted, due October 6

More about BOOLEAN issues

Pointers. 10/5/07 Pointers 1

Binary Representation. Decimal Representation. Hexadecimal Representation. Binary to Hexadecimal

Decimal Representation

Lecture 4. Default Arguments. Set defaults in function prototype. int myfunction( int x = 1, int y = 2, int z = 3 );

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

What is an algorithm?

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

Variation of Pointers

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

Tutorial 10 Pointers in C. Shuyue Hu

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

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

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

Lecture 04 Introduction to pointers

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

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

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

School of Science and Technology

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

Pointers as Arguments

Work relative to other classes

Lecture 3. More About C

DECLARAING AND INITIALIZING POINTERS

COMP26120: Linked List in C (2018/19) Lucas Cordeiro

Homework #3 CS2255 Fall 2012

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

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

A pointer is a variable just like other variable. The only difference from other variables is that it stores the memory address other variables.

CSCI 171 Chapter Outlines

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

Operators & Expressions

Chapter 5 - Pointers and Strings

Fundamental of Programming (C)

Chapter 5 - Pointers and Strings

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Review of the C Programming Language for Principles of Operating Systems

Content. In this chapter, you will learn:

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

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

Procedural programming with C

A flow chart is a graphical or symbolic representation of a process.

Variables and Operators 2/20/01 Lecture #

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University

Fundamentals of Programming

Pointer. Pointer variable

Computer Programming Lecture 12 Pointers

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

BLM2031 Structured Programming. Zeyneb KURT

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

Chapter 2, Part III Arithmetic Operators and Decision Making

Intermediate Programming, Spring 2017*

Goals of this Lecture

CSC 211 Intermediate Programming. Pointers

Relationship between Pointers and Arrays

today cs3157-fall2002-sklar-lect05 1

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

Programming in C - Part 2

Pointers in C/C++ 1 Memory Addresses 2

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Transcription:

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 Tuesday, 2-3 Thursday Textbook: C How to Program (chapter 7) These slides are based on the lectures notes of C How to Program 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.

Intended learning outcomes To learn about pointers and pointer operations To use pointers to pass arguments to functions by reference To understand the close relationships among pointers, arrays, and strings To use pointers to functions To define and use arrays of strings

Introduction Pointers enable programs to simulate pass-by-reference int x=2; void square(int *nptr){! *nptr *= *nptr; }! int main(void) {! square (&x);! return 0;!! } What are the advantages and disadvantages to pass arguments to functions by reference?

Introduction Pointers enable programs to simulate pass-by-reference use function pointers #include <stdio.h>! typedef void (*functiontype)(int x);! void dosomething(int x){! printf( x: %d\n, x);! }! int main(void){! functiontype func = &dosomething;! func(2);! return 0;! }! What is the common use of function pointers?

Introduction Pointers enable programs to simulate pass-by-reference use function pointers create and manipulate dynamic data structures entry *allocate_entries(int num_entries){! entry *entriesptr = (entry*)malloc(sizeof(entry)! * num_entries);! for (int i = 0 ; i < num_entries; i++) init_entry(&entriesptr[i]); return entriesptr;! } Next class: dynamic memory management

Pointer Variable Definitions and Initialization Pointers are variables whose values are memory addresses A variable directly contains a specific value A pointer contains an address of a variable that contains a specific value a variable name directly references a value, and a pointer indirectly references a value Referencing a value through a pointer is called indirection

Declaring Pointers Pointers, like all variables, must be defined before they can be used The definition int *countptr, count; void *speedptr; How can we interpret these definitions? Pointers can be defined to point to objects of any type

Common Programming Error The asterisk (*) notation used to declare pointer variables does not distribute to all variable names in a declaration Each pointer must be declared with the * prefixed to the name xptr and yptr must be declared as *xptr and *yptr Include the letters ptr in pointer variable names make it clear that these variables are pointers need to be handled appropriately

Initialising and Assigning Values to Pointers Pointers should be initialised when they re defined A pointer may be initialised to NULL, 0 or an address A pointer with the value NULL points to nothing Initializing a pointer to 0 is equivalent to initialising a pointer to NULL, but NULL is preferred NULL is a symbolic constant defined in the <stddef.h> header (and other headers, <stdio.h>) Initialise pointers to prevent unexpected results

Pointer Operators The &, or address operator, is a unary operator that returns the address of its operand For example, assuming the definitions int y = 5; int *yptr; the statement yptr = &y; assigns the address of the variable y to pointer variable yptr Variable yptr is then said to point to y

Pointer Representation in Memory Assume that integer variable y is stored at location 600000, and pointer variable yptr is stored at location 500000 The operand of the address operator must be a variable the address operator cannot be applied to constants or expressions

The Indirection (*) Operator The unary * operator: indirection operator or dereferencing operator returns the object value to which its operand points For example, the statement printf("%d", *yptr); prints the value of variable y, namely 5 Using * here is called dereferencing a pointer Dereferencing a pointer that has not been initialised or that has not been assigned to point to a specific location in memory is an error

%p outputs the memory location as a hexadecimal integer on most platforms

the address of a is indeed assigned to the pointer variable aptr The & and * operators are complements of one another when they re both applied consecutively to aptr in either order, the same result is printed

Exercise Answer each of the following: a) A pointer variable contains as its value the of another variable? b) The three values that can ne used to initialise a pointer are, and. c) The only integer that can be assigned to a pointer is. d) The address operator can be applied only to.

Passing Arguments to Functions by Reference There are two ways to pass arguments to a function: pass-by-value and pass-by-reference All arguments in C are passed by value Many functions require the capability to modify variables in the caller or pass a pointer to a large data object To avoid the time and memory overheads In C, you use pointers and the indirection operator to simulate pass-by-reference

Use call-by-value to pass arguments to a function to prevent accidental modification of the caller s argument

Use pass-by-reference only if the caller explicitly requires the called function to modify the value of the argument variable in the caller s environment

Passing Arguments to Functions by Reference (Cont.) For a function that expects one-dimensional array, its prototype and header can use pointer notation No difference between a function that receives a pointer and one that receives a one-dimensional array the function must know when it s receiving an array or a single variable to perform pass-by-reference The compiler converts int b[] to the pointer notation int *b

Step 2 Step 1 Step 1

Step 3 Step 4 Step 4

sizeof Operator C provides the special unary operator sizeof to determine the size in bytes of an array (or any other data type) sizeof is a compile-time operator, so it does not incur any execution-time overhead

When applied to the name of an array, the sizeof operator returns the total number of bytes in the array as type size_t Variables of type float on this computer are stored in 4 bytes of memory, and array is defined to have 20 elements Therefore, there are a total of 80 bytes in array

Exercise Consider the following array definition: double real[22]; What is the total number of bytes? The number of elements in an array also can be determined with sizeof Variables of type double normally are stored in 8 bytes of memory Thus, array real contains a total of 176 bytes How can you determine the total number of elements? To determine the number of elements in the array, the following expression can be used: sizeof(real) / sizeof(real[0])

Pointer Expressions and Pointer Arithmetic Pointers are valid operands in arithmetic expressions, assignment expressions and comparison expressions A pointer may be incremented (++) or decremented (--) an integer may be added to a pointer (+ or +=) an integer may be subtracted from a pointer (- or -=) one pointer may be subtracted from another if both pointers point to elements of the same array

Pointer Arithmetic Example int v[5]; int *vptr; vptr = v; machine with 4-byte integers Since the results of pointer arithmetic depend on the size of the objects a pointer points to, pointer arithmetic is machine dependent

Pointer Arithmetic Example When an integer is added to or subtracted from a pointer, the pointer is not incremented or decremented simply by that integer, By that integer times the size of the object to which the pointer refers The number of bytes depends on the object s data type What this statement would produce? vptr += 2; it would produce 3008 (3000 + 2 * 4), assuming an integer is stored in 4 bytes of memory In the array v, vptr would now point to v[2]

Using pointer arithmetic on a pointer that does not refer to an element in an array is a common programming error

Pointer Expressions and Pointer Arithmetic (Cont.) A pointer can be assigned to another pointer if both have the same type The exception to this rule is the pointer to void (i.e., void *), which is a generic pointer that can represent any pointer type All pointer types can be assigned a pointer to void, and a pointer to void can be assigned a pointer of any type In both cases, a cast operation is not required A pointer to void cannot be dereferenced

Pointer Expressions and Pointer Arithmetic (Cont.) The compiler knows that a pointer to int refers to 4 bytes of memory on a machine with 4-byte integers however, a pointer to void simply contains a memory location for an unknown data type the precise number of bytes to which the pointer refers is not known by the compiler The compiler must know the data type to determine the number of bytes to be dereferenced for a particular pointer

Pointer Expressions and Pointer Arithmetic (Cont.) Pointers can be compared using equality and relational operators, but such comparisons need to point to elements of the same array Pointer comparisons compare the addresses stored in the pointers A comparison of two pointers pointing to elements in the same array could show that one pointer points to a higher-numbered element of the array than the other pointer does A common use of pointer comparison is determining whether a pointer is NULL

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 to do any operation involving array indexing Assume that integer array b[5] and integer pointer variable have been defined Attempting to modify an array name with pointer arithmetic is a compilation error (e.g., b+=3)

Exercise Find the error in each of the following program segments: int *zptr; int *aptr = NULL; void *sptr = NULL; int number, i; int z[5] = {1, 2, 3, 4, 5}; sptr = z; a) ++zptr; b) number = zptr; c) number = *zptr[2]; d) number = *sptr; e) ++z;

Using the const Qualifier with Pointers The const qualifier indicates that the value of a particular variable should not be modified Reduce debugging time and improper side effects It also makes a program easier to modify and maintain Ensure that data is not accidentally modified If an attempt is made to modify a value that s declared const, the compiler catches it and issues either a warning or an error

Using the const Qualifier with Pointers (Cont.) Access privileges Non-Constant Pointer Non-Constant Data Constant Pointer Constant Data Which combination provides the highest level of data access?

Example of Non-Constant Pointer to Constant Data A non-constant pointer to constant data can be modified to point to any data item of the appropriate type, but the data to which it points cannot be modified

Attempt to Modify Data via a Non- Constant Pointer to Constant Data The next example 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 which results in a compilation error

Trade-off Memory and Execution Efficiency If memory is low and execution efficiency is a concern, use pointers If memory is in abundance and efficiency is not a major concern, pass data by value to enforce the principle of least privilege Remember that some systems do not enforce const well, so pass-by-value is still the best way to prevent data from being modified

Attempting to Modify a Constant Pointer to Non-Constant Data A constant pointer to non-constant data always points to the same memory location the data at that location can be modified through the pointer This is the default for an array name (constant pointer) All data in the array can be accessed and changed by using the array name and array indexing a+=2 int a[5]; 0 2 4 6 8 for(int i=0; i<5; i++) a[i] = 2*i; invalid operands to binary expression ('const int [5]' and 'int')

Attempting to Modify a Constant Pointer to Constant Data The least access privilege is granted by a constant pointer to constant data Such a pointer always points to the same memory location, and the data at that memory location cannot be modified const int a[5]; 10 2 5 20 1 a[1]=2 for(int i=0; i<5; i++) printf( a[%i]: %i\n, i, a[i]); read-only variable is not assignable

Summary Pointer variable definition and initialization Pointer operators Passing arguments to functions by reference Using the const qualifier with pointers sizeof operator Pointer expression and pointer arithmetic Relationship between pointers and arrays