Pointers in C. Address vs. Value. Another Need for Addresses. Executing the Swap Function

Similar documents
Homework 3 Solutions

Section 5-4 Trigonometric Functions

Binary Representation of Numbers Autar Kaw

Object Semantics Lecture 2

Virtual Machine. Part II: Program Control. Building a Modern Computer From First Principles.

A.7.1 Trigonometric interpretation of dot product A.7.2 Geometric interpretation of dot product

Use Geometry Expressions to create a more complex locus of points. Find evidence for equivalence using Geometry Expressions.

EQUATIONS OF LINES AND PLANES

Bayesian Updating with Continuous Priors Class 13, 18.05, Spring 2014 Jeremy Orloff and Jonathan Bloom

Reasoning to Solve Equations and Inequalities

Protocol Analysis / Analysis of Software Artifacts Kevin Bierhoff

1.00/1.001 Introduction to Computers and Engineering Problem Solving Fall Final Exam

Small Business Networking

AntiSpyware Enterprise Module 8.5

Regular Sets and Expressions

2 DIODE CLIPPING and CLAMPING CIRCUITS

Polynomial Functions. Polynomial functions in one variable can be written in expanded form as ( )

1.2 The Integers and Rational Numbers

PROF. BOYAN KOSTADINOV NEW YORK CITY COLLEGE OF TECHNOLOGY, CUNY

Appendix D: Completing the Square and the Quadratic Formula. In Appendix A, two special cases of expanding brackets were considered:

MA Lesson 16 Notes Summer 2016 Properties of Logarithms. Remember: A logarithm is an exponent! It behaves like an exponent!

9 CONTINUOUS DISTRIBUTIONS

Small Business Networking

Helicopter Theme and Variations

Or more simply put, when adding or subtracting quantities, their uncertainties add.

Small Business Networking

and thus, they are similar. If k = 3 then the Jordan form of both matrices is

Small Business Networking

Morgan Stanley Ad Hoc Reporting Guide

Integration by Substitution

Experiment 6: Friction

Answer, Key Homework 10 David McIntyre 1

Welch Allyn CardioPerfect Workstation Installation Guide

IaaS Configuration for Virtual Platforms

How To Network A Smll Business

Learning Outcomes. Computer Systems - Architecture Lecture 4 - Boolean Logic. What is Logic? Boolean Logic 10/28/2010

NQF Level: 2 US No: 7480

Network Configuration Independence Mechanism

DATABASDESIGN FÖR INGENJÖRER F

Vectors Recap of vectors

How fast can we sort? Sorting. Decision-tree model. Decision-tree for insertion sort Sort a 1, a 2, a 3. CS Spring 2009

BUSINESS OWNERS PACKAGE INSURANCE APPLICATION

LINEAR TRANSFORMATIONS AND THEIR REPRESENTING MATRICES

Factoring Polynomials

Pentominoes. Pentominoes. Bruce Baguley Cascade Math Systems, LLC. The pentominoes are a simple-looking set of objects through which some powerful

Start Here. IMPORTANT: To ensure that the software is installed correctly, do not connect the USB cable until step 17. Remove tape and cardboard

According to Webster s, the

FAULT TREES AND RELIABILITY BLOCK DIAGRAMS. Harry G. Kwatny. Department of Mechanical Engineering & Mechanics Drexel University

Graphs on Logarithmic and Semilogarithmic Paper

Treatment Spring Late Summer Fall Mean = 1.33 Mean = 4.88 Mean = 3.

5.6 POSITIVE INTEGRAL EXPONENTS

Chapter. Contents: A Constructing decimal numbers

Words Symbols Diagram. abcde. a + b + c + d + e

Example 27.1 Draw a Venn diagram to show the relationship between counting numbers, whole numbers, integers, and rational numbers.

trademark and symbol guidelines FOR CORPORATE STATIONARY APPLICATIONS reviewed

One Minute To Learn Programming: Finite Automata

STRM Log Manager Installation Guide

Unit 6: Exponents and Radicals

MATH 150 HOMEWORK 4 SOLUTIONS

How To Set Up A Network For Your Business

15.6. The mean value and the root-mean-square value of a function. Introduction. Prerequisites. Learning Outcomes. Learning Style

Math 135 Circles and Completing the Square Examples

New Internet Radio Feature

Tablet Charging Wall Mount 12

Firm Objectives. The Theory of the Firm II. Cost Minimization Mathematical Approach. First order conditions. Cost Minimization Graphical Approach

Algebra Review. How well do you remember your algebra?

MATH PLACEMENT REVIEW GUIDE

Quick Reference Guide: One-time Account Update

Section 5.2, Commands for Configuring ISDN Protocols. Section 5.3, Configuring ISDN Signaling. Section 5.4, Configuring ISDN LAPD and Call Control

Mathematics. Vectors. hsn.uk.net. Higher. Contents. Vectors 128 HSN23100

P.3 Polynomials and Factoring. P.3 an 1. Polynomial STUDY TIP. Example 1 Writing Polynomials in Standard Form. What you should learn

Lecture 5. Inner Product

FUNCTIONS AND EQUATIONS. xεs. The simplest way to represent a set is by listing its members. We use the notation

5 a LAN 6 a gateway 7 a modem

Section 7-4 Translation of Axes

Quick Guide to Lisp Implementation

Vendor Rating for Service Desk Selection

Java CUP. Java CUP Specifications. User Code Additions You may define Java code to be included within the generated parser:

Physics 43 Homework Set 9 Chapter 40 Key

Lec 2: Gates and Logic

9.3. The Scalar Product. Introduction. Prerequisites. Learning Outcomes

Integration. 148 Chapter 7 Integration

Multiplication and Division - Left to Right. Addition and Subtraction - Left to Right.

body.allow-sidebar OR.no-sidebar.home-page (if this is the home page).has-custom-banner OR.nocustom-banner .IR OR.no-IR

, and the number of electrons is -19. e e C. The negatively charged electrons move in the direction opposite to the conventional current flow.

VMware Horizon Mirage Web Manager Guide

Rotating DC Motors Part II

Small Businesses Decisions to Offer Health Insurance to Employees

baby on the way, quit today

0.1 Basic Set Theory and Interval Notation

Two hours UNIVERSITY OF MANCHESTER SCHOOL OF COMPUTER SCIENCE. Date: Friday 16 th May Time: 14:00 16:00

We will begin this chapter with a quick refresher of what an exponent is.

Example A rectangular box without lid is to be made from a square cardboard of sides 18 cm by cutting equal squares from each corner and then folding

flex Regular Expressions and Lexical Scanning Regular Expressions and flex Examples on Alphabet A = {a,b} (Standard) Regular Expressions on Alphabet A

T H E S E C U R E T R A N S M I S S I O N P R O T O C O L O F S E N S O R A D H O C N E T W O R K

Small Business Cloud Services

1. Find the zeros Find roots. Set function = 0, factor or use quadratic equation if quadratic, graph to find zeros on calculator

Babylonian Method of Computing the Square Root: Justifications Based on Fuzzy Techniques and on Computational Complexity

JaERM Software-as-a-Solution Package

Transcription:

Address vs. Vlue Sometimes we wnt to del with the ddress of memory loction, rther thn the vlue it contins Pointers in C Bsed on slides McGrw-Hill Additionl mteril 200/2005 Lewis/Mrtin Modified y Din Plseti Adding column of numers in LC-: R2 contins ddress of loction Red vlue, dd to sum, nd increment R2 until ll numers hve een processed R2 is pointer It contins the ddress of dt R2 x100 ddress vlue x107 x2819 x0110 x010 x0100 x1110 x11b1 x0019 x100 x101 x102 x10 x10 x105 x106 x107 CIT 59 2 Another Need for Addresses Consider the following function tht's supposed to swp the vlues of its rguments. void swp(int, int ){ int temp = ; = ; = temp; int min(){ int = ; int = ; swp(,); CIT 59 Executing the Swp Function efore cll fter cll swp min temp These vlues chnged... Swp needs ddresses of vriles outside its own ctivtion record...ut these did not. CIT 59 1

Pointers in C C lets us mnipulte ddresses s vriles nd in use them in expressions. Declrtion int *p; /* p is pointer to n int */ A pointer in C is lwys pointer to prticulr dt type: int*, doule*, chr*, etc. Opertors *p -- returns the vlue pointed to y p.k. de-referencing pointer &z -- returns the ddress of vrile z int min(){ int i; int *ptr; Exmple store the vlue into the memory loction ssocited with i i = ; ptr = &i; *ptr = *ptr + 1; printf( %d\n, i); store the ddress of i into the memory loction ssocited with ptr xeffb xeffd xeffe 5 ptr i red the contents of memory t the ddress stored in ptr nd increment it y 1 Vlue of i will e 5, ecuse i ws modified indirectly vi ptr CIT 59 5 CIT 59 6 Exmple: LC- Code ; i is (offset 1), ptr (offset 0 i.e. the lst locl vrile dded to stck frme) ; i = ; AND R0, R0, #0 ; cler R0 ADD R0, R0, # ; put in R0 ADD R6, R6, #-1 ;djust stck pointer STR R0, R6, #0 ; store in i on top of stck ; int *ptr = &i; ADD R0, R6, #0 ; R0 = R6 + 0 (ddr of i) ADD R6, R6, -1 ;crete spce for ptr STR R0, R6, #0 ; store ddr of i in ptr AND R5, R5, #0 ADD R5, R6, #0 ;min s frme pointer ; *ptr = *ptr + 1; LDR R0, R5, #0 ; R0 = contents of ptr i.e. ddress of i LDR R1, R0, #0 ; lod contents (*ptr) ADD R1, R1, #1 ; dd one STR R1, R0, #0 ; store to ddress of i CIT 59 7 Pointers s Arguments Pssing pointer into function llows the function to red/chnge memory outside its ctivtion record void swp(int *, int *) { int temp = *; * = *; * = temp; Arguments re integer pointers. Cller psses ddresses of vriles tht t it wnts function to chnge CIT 59 8 2

Pssing Pointers to Function Code Using Pointers min() wnts to swp the vlues of nd psses the ddresses to swp(): swp(&, &); Code for pssing rguments: ADD R0, R5, #0 ; ddr of ADD R6, R6, #-1; R5 (Min s FP) STR R0, R6, #0 ADD R0, R5, #1 ; ddr of ADD R6, R6, #-1; STR R0, R6, #0 xeffb xeffd xeffe temp Inside the swp() routine ; int temp = *; LDR R0, R5, #7 ; R0= LDR R1, R0, #0 ; R1=M[]= STR R1, R5, #0 ; temp= ; * = *; LDR R1, R5, #8 ; R1= LDR R2, R1, #0 ; R2=M[]= STR R2, R0, #0 ; M[]= ; * = temp; LDR R2, R5, #0 ; R2=temp= STR R2, R1, #0 ; M[]= R5 xeffb xeffd xeffe R5 R2 R1 R0 R7 ret vl temp CIT 59 9 CIT 59 10 Using Arguments for Results Pss ddress of vrile where you wnt result stored Exmple: scnf("%d %d", &dt1, &dt2); red deciml integers into dt1 nd dt2 1. Argument is not n ddress int n = 0; scnf("%d", n); Bd scnf Arguments Will use the vlue of the rgument s n ddress If you're lucky, progrm will crsh ecuse of trying to modify restricted memory loction (e.g., loction 0) Runtime error: Segmenttion Fult 2. Missing dt rgument scnf("%d"); Your progrm will just modify n ritrry memory loction, which cn cuse very unpredictle ehvior Becuse it will get ddress from stck, where it expects to find dt rgument CIT 59 11 CIT 59 12

Null Pointer Sometimes we wnt pointer tht points to nothing. In other words, we declre pointer, ut we re not redy to ctully point to something yet. int *p; p = NULL; /* p is null pointer */ NULL is predefined mcro tht contins vlue tht non-null pointer should never hold. Often, NULL = 0, ecuse Address 0 is not legl ddress for most progrms on most pltforms Dereferencing NULL pointer: progrm crsh! int *p = NULL; printf( %d, *p); // CRASH! Output: Segmenttion fult CIT 59 1 Exmples: Pointer Prolems Wht does this do? int *x; *x = 10; Answer: writes 10 into rndom loction in memory Wht s wrong with: int* func(){ int x = 10; return &x; Answer: storge for x disppers on return, so the returned pointer is dngling A dngling pointer is pointer to storge element(int, chr, doule etc) tht is no longer llocted CIT 59 1 Declring Pointers The * opertor inds to the vrile nme, not the type All the sme: int* x, y; int *x, y; int *x; int y; Suggested solution: Declre only one vrile per line Avoids this prolem Esier to comment Clerer Don t worry out sving spce Arry s Locl Vrile Arry elements re llocted s prt of the ctivtion record int grid[10]; First element (grid[0]) is t lowest ddress of llocted spce grid[0] grid[1] grid[2] grid[] grid[] grid[5] grid[6] grid[7] grid[8] grid[9] CIT 59 15 CIT 59 16

LC- Code for Arry References ; x = grid[] + 1 ADD R0, R5, #1 ; R0 = &grid[0] LDR R1, R0, # ; R1 = grid[] ADD R1, R1, #1 ; R1 = R1 + 1 STR R1, R5, #0 ; x = R1 ; grid[6] = 5; AND R0, R0, #0 ADD R0, R0, #5 ; R0 = 5 ADD R1, R5, #1 ; R1 = &grid[0] STR R0, R1, #6 ; grid[6] = R0 R5 x grid[0] grid[1] grid[2] grid[] grid[] grid[5] grid[6] grid[7] grid[8] grid[9] Reltionship etween Arrys nd Pointers An rry nme is essentilly pointer to the element in the rry chr dt[10]; i.e. dt = ddr where element is locted = &dt[0] Exmple: chr dt[10]; chr *cptr; cptr = dt; /* points to dt[0] */ CIT 59 17 CIT 59 18 Correspondence etween Ptr nd Arry Nottion Given the declrtions on the previous pge, ech line elow gives three equivlent expressions: cptr dt &dt[0] (cptr + n) (dt + n) &dt[n] *cptr *dt dt[0] *(cptr + n) *(dt + n) dt[n] Bewre Arrys re not the sme s pointers lthough they my look like wht is the difference etween rrys nd pointers? Arrys utomticlly llocte spce, ut cn't e relocted or resized. Pointers must e explicitly ssigned to point to llocted spce ut cn e ressigned (i.e. pointed t different ojects) t will, nd hve mny other uses esides serving s the se of locks of memory. CIT 59 19 CIT 59 20 5

Pointer Arithmetic: Sutrction nd Equlity Nsty, ut C llows it: void function(int* strt, int* end) { int i; while (end - strt >= 0) { *strt t = 0; strt++; In function min(): int rry[10]; function(&rry[0], &rry[9]); Don t do this! Alterntive: while (end!= strt) { Significntly etter, ut still d Wht if strt is > end, or not prt of sme rry? CIT 59 21 More on Pointer Arithmetic Address clcultions depend on size of elements In our LC- code, we've een ssuming one word per element e.g., to find th element, we dd to se ddress It's ok, ecuse we've only shown code for int, which h tkes up one word (equl to mchine width). If doule, we'd hve to dd 8 to find ddress of th element. C does size clcultions under the covers, depending on size of item eing pointed to: doule x[10]; doule *y = x; *(y + ) = 100; sme s x[] -- se ddress plus 6 lloctes 20 words (2 per element) CIT 59 22 Pointer-to-Pointer The declrtion of pointer-to-pointer looks like int **ipp; Exmple: int i = 5 int *ip1 = &i, int ** ipp = &ip1; C vs. Jv C Pointers mkes it unsfe s there is no compile time checking on: Dereferencing null pointer Hving dngling pointer Cn esily right to memory spce eyond wht you declred No limit checking for rry length Jv removes unsfe fetures y not supporting the unry & ddress opertor supporting ddress rithmetic on references i.e. does not llow integer vlues to e dded/sutrcted to references CIT 59 2 CIT 59 2 6