A brief intro to pointers for the purposes of passing reference parameters

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

Parameter passing. Programming in C. Important. Parameter passing... C implements call-by-value parameter passing. UVic SEng 265

Memory and Addresses. Pointers in C. Memory is just a sequence of byte-sized storage devices.

Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance. John Edgar 2

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

APS105. Pointers. Memory RAM 11/5/2013. Pointers. Need a way to refer to locations of things. a pointer: Address. Example: In C

Lecture 04 Introduction to pointers

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

Procedural programming with C

Arrays. Here is the generic syntax for an array declaration:

C-1. Overview. CSE 142 Computer Programming I. Review: Computer Organization. Review: Memory. Declaring Variables. Memory example

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #34. Function with pointer Argument

Tutorial 5. Call Stack and Stack Frames. Memory Addresses and Pointers. Content vs Address of Pointers. scanf() function. Perils of Pointers

Lecture 5: Multidimensional Arrays. Wednesday, 11 February 2009

Functions. Arash Rafiey. September 26, 2017

CSCI 2132 Software Development. Lecture 17: Functions and Recursion

CSCI 2132 Software Development. Lecture 18: Functions

At the end of this module, the student should be able to:

CSE / ENGR 142 Programming I

Computer Programing. for Physicists [SCPY204] Class 02: 25 Jan 2018

CS2351 Data Structures. Lecture 7: A Brief Review of Pointers in C

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

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

Unit 3 Functions. 1 What is user defined function? Explain with example. Define the syntax of function in C.

Physics 306 Computing Lab 5: A Little Bit of This, A Little Bit of That

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

Decimal Representation

Object oriented programming C++

Programming Studio #9 ECE 190

Introduction to Scientific Computing and Problem Solving

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57

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

EM108 Software Development for Engineers

Arrays Arrays and pointers Loops and performance Array comparison Strings. John Edgar 2

Full file at

SYSC 2006 C Winter 2012

Linked-List Basic Examples. A linked-list is Linear collection of self-referential class objects, called nodes Connected by pointer links

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

[0569] p 0318 garbage

Slides adopted from T. Ferguson Spring 2016

Array Initialization

UNIVERSITY OF WINDSOR Fall 2007 QUIZ # 2 Solution. Examiner : Ritu Chaturvedi Dated :November 27th, Student Name: Student Number:

Lab Session # 1 Introduction to C Language. ALQUDS University Department of Computer Engineering

Arrays in C. Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute of Technology Kharagpur. Basic Concept

Pointers. Pointers. Pointers (cont) CS 217

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

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

Computer Programming Lecture 12 Pointers

Lecture 9 - C Functions

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

printf("this program adds the value 10 to a given integer number.\n\n");

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type

CSCI 2132 Software Development. Lecture 19: Generating Permutations

A brief introduction to C programming for Java programmers

10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013

return return else return

BSM540 Basics of C Language

EECE.2160: ECE Application Programming Spring 2016 Exam 1 Solution

APSC 160 Review Part 2

Pointers and scanf() Steven R. Bagley

APSC 160 Review. CPSC 259: Data Structures and Algorithms for Electrical Engineers. Hassan Khosravi Borrowing many questions from Ed Knorr

ESc101: Pointers and Arrays

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

Structures in C. C allows you to declare a struct. Once you do so, you can create variables of this type. Here is the general syntax:

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, SPRING 2013

C Pointers 2013 Author Riko H i

Variables, Pointers, and Arrays

Chapter 8. Arrays, Addresses, and Pointers : Structured Programming Structured Programming 1

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

16.216: ECE Application Programming Fall 2011

Today s Learning Objectives

Arrays and Strings. Antonio Carzaniga. February 23, Faculty of Informatics Università della Svizzera italiana Antonio Carzaniga

CSC 270 Survey of Programming Languages

Pointers. 10/5/07 Pointers 1

& Technology. G) Functions. void. Argument2, Example: (Argument1, Syllabus for 1. 1 What. has a unique. 2) Function name. passed to.

a data type is Types

References and pointers

Week 4. This is CS50. Harvard University. Fall Anna Whitney

notice the '' you must have those around character values, they are not needed for integers or decimals.

Lecture 02 Summary. C/Java Syntax 1/14/2009. Keywords Variable Declarations Data Types Operators Statements. Functions

2SKILL. Variables Lesson 6. Remembering numbers (and other stuff)...

Online Judge and C. Roy Chan. January 12, Outline Information Online Judge Introduction to C. CSC2100B Data Structures Tutorial 1

CS 2461: Computer Architecture I

16.216: ECE Application Programming Fall 2011

16.216: ECE Application Programming Fall 2015 Exam 1 Solution

Pointers. Lecture 1 Sections Robb T. Koether. Hampden-Sydney College. Wed, Jan 14, 2015

b. array s first element address c. base address of an array d. all elements of an array e. both b and c 9. An array elements are always stored in a.

Programming Language B

Pointers and Functions Passing Pointers to Functions CMPE-013/L. Pointers and Functions. Pointers and Functions Passing Pointers to Functions

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Introduction to arrays

CSE 333 Lecture 2 - arrays, memory, pointers

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012

CSCI 2021: Introduction

COP 3223 Introduction to Programming with C - Study Union - Spring 2018

Chapter 4. Section 4.4 Passing Parameters to Functions. CS 50 Hathairat Rattanasook

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

Lecture Notes on Memory Layout

Intermediate Programming, Spring 2017*

Transcription:

A brief intro to pointers for the purposes of passing reference parameters With respect to functions, we have only talked about pass by value parameters. Today we will discuss pass by reference parameters. But, in order to use these, we have to understand a bit about how pointers work in C. A computer's memory can be visualized as a very long numbered array of bytes. Each byte of memory is numbered with it's address. Perhaps a simple analogy would be that each byte of memory is a house on a really long street. Each of these houses are numbered in order. If you ever want to retrieve a value in a house, one way you could do so is use the correct street address. This is what a pointer is - a street address directing you to where some information is stored. However, this is not how you access or manipulate information usually. Instead, you create a variable through a declaration. Internally, when you declare a variable, what the computer does is find a "house" to store that variable. Once a house is found, it keeps a list of all the declared variables and the houses they live in. Anytime in your program you refer to a variable, it automatically goes to the contents of the house that match the address given on the main list. In some sense, you are referring to the house by who lives there. (The computer takes care of looking up where that person lives...) What a pointer allows you to do is access a variable, without using a name for it. Instead, a pointer just stores a location in memory, and through that pointer, you are allowed to change the value of the variable stored at that location.

First, let's go through the basic syntax of how to declare a pointer: int *p; This literally says to create a variable p. The type of the variable p is a "pointer to an integer," not just a "pointer." p can not store a value, but it can store a memory address. Now, let's say we have the added declaration: int a = 7; One statement that is useful with pointers is to assign them a location to point. However, this statement: p = a; is illegal? Why? Instead, we need a way to find the memory address of where the variable a is stored to make this a valid statement. We can do this with the "address of" operator, &. The correct statement is p = &a; Basically here is what these three statements are doing in memory:

The other thing we want to be able to do is to access a variable that a pointer is pointing to. We can do this through the "dereferencing" operator, *. Notice that * is used in two different ways. When we declare a pointer, we use * to denote that a variable is a pointer. But NOW, we see that the * allows us to dereference a pointer as well. Here is an example of what we can do: *p = 3; This says to find the variable that p is pointing to and change it to 3. Since this variable is a, you'll see that if we printed out the value of a: printf("a = %d\n",a) The output would be a = 3. Thus, we were able to change the value of a without directly using the identifier a. This is because p was pointing to where a was stored. These are essentially all the mechanics we need in order to use pass by reference variables.

How could pass by reference variables help us? One "subtask" that is common in many computer programs is swapping the value of two variables. (One of our solutions to the desk problem included a swap.) Imagine writing a function that performs such a swap with two integer variables, it would look something like this: void swap(int a, int b) { int temp; temp = a; a = b; b = temp; Now, imagine a segment of code in main as follows: int x = 3, y = 7; swap(x,y); printf("x = %d, y= %d\n",x,y); What would get printed out? Why? So the problem here is that no matter what swap does, as long as it takes in pass by value parameters, the values of x and y are guaranteed to be what they were before the swap function call.

In essence, it may be desirable to have a function that has the ability to manipulate variables that are locally declared in other functions. Pointers allow you to refer to a variable without using its name. Thus, if we can pass pointers are parameters, perhaps there is a way around the apparent pass-by-value problem: void swap(int *p, int *q) { int temp; temp = *p; *p = *q; *q = temp; It's important to note that in the formal parameter definition, * means pointer, but in the code, it is the dereferencing operator. So, now the question becomes, how do we CALL this function. You'll notice that the types of the formal parameters are NOT ints, but "pointers to ints." Thus, when we call the swap function, we can not pass actual parameters that are integers, we must pass parameters that are pointers to ints. Here is how we would do that: int x = 3, y = 7; swap(&x, &y); printf("x = %d, y= %d\n",x,y); Remember that &x is read as "address of x." This is a pointer - exactly what we want to pass to the function swap. Let's trace through the code written above:

#include <stdio.h> A simple pass by reference example void deposit(int* accnt_bal); void withdraw(int* accnt_bal); void menu(); int main() { int balance; char ans; // Read in starting balance printf("enter your starting balance.\n"); scanf("%d", &balance); // Loop until user quits main menu. menu(); scanf("%c", &ans); while (ans!= '3') { // Execute appropriate menu option. if (ans == '1') deposit(&balance); else if (ans == '2') withdraw(&balance); else if (ans!= '3') printf("invalid menu choice, please try again.\n") menu(); scanf("%c", &ans); return 0;

// Pre-condition: accnt_bal is the current bank balance. // Post-condition: The bank balance will be adjusted according // to what the user enters as their deposit. // No negative deposits are processed. void deposit(int* accnt_bal) { // Read in deposit. int dep; printf("enter the amount of your deposit.\n"); scanf("%d", &dep); // Only adjust balance if necessary. if (dep > 0) *accnt_bal += dep; else printf("that deposit can not be executed.\n"); // Pre-conditions: none // Post-condition: Menu for the bank program will get printed. void menu() { printf("please enter your next menu selection.\n"); printf("1. Deposit money to your account.\n"); printf("2. Withdraw money from your account.\n"); printf("3. Quit this program.\n"); Class Exercise: Write the withdraw function.

int f1(int *a, int b); int f2(int a, int *b); int main() { Tracing Question for next time int a = 5, b = 2, c = 7, d = 9; c = f1(&d, a); printf("a=%d,b=%d,c=%d,d=%d\n",a,b,c,d); a = f2(c - d, &a); printf("a=%d,b=%d,c=%d,d=%d\n",a,b,c,d); b = f1(&c, 8); printf("a=%d,b=%d,c=%d,d=%d\n",a,b,c,d); d = f2(b, &a); printf("a=%d,b=%d,c=%d,d=%d\n",a,b,c,d); int f1(int *a, int b) { *a = b - 8; b = b*2 - (*a); printf("a=%d,b=%d\n",*a,b); return b - *a; int f2(int a, int *b) { a = *b + a; *b = 37 - *b; printf("a=%d,b=%d\n",a,*b); return a;