Pointers and Variables: Definition. Phys4051: C Lectures. Pointers: Operators (1) Pointers: Operators (2) Assigning an Address to a Pointer (1)

Similar documents
arrays C Programming Language - Arrays

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Sources: On the Web: Slides will be available on:

Lecture 22: C Programming 4 Embedded Systems

In this Chapter you ll learn:

Tutorial on C Language Programming

Conditionals (with solutions)

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

13 Classes & Objects with Constructors/Destructors

Dalhousie University CSCI 2132 Software Development Winter 2015 Lab 7, March 11

Passing 1D arrays to functions.

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

The C Programming Language course syllabus associate level

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

(Refer Slide Time: 00:01:16 min)

6.S096 Lecture 1 Introduction to C

Parameter Passing. Standard mechanisms. Call by value-result Call by name, result

C Programming. Charudatt Kadolkar. IIT Guwahati. C Programming p.1/34

Data Structures using OOP C++ Lecture 1

Implementation Aspects of OO-Languages

recursion, O(n), linked lists 6/14

C Interview Questions

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

The Function Pointer

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Parameter Passing. Parameter Passing. Parameter Passing Modes in Fortran. Parameter Passing Modes in C

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

Introduction to Data Structures

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

Student Outcomes. Lesson Notes. Classwork. Discussion (10 minutes)

FEEG Applied Programming 5 - Tutorial Session

C++ DATA STRUCTURES. Defining a Structure: Accessing Structure Members:

1 Abstract Data Types Information Hiding

What Is Recursion? Recursion. Binary search example postponed to end of lecture

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

CSI 402 Lecture 13 (Unix Process Related System Calls) 13 1 / 17

Analysis of a Search Algorithm

The Clean programming language. Group 25, Jingui Li, Daren Tuzi

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

PicoScope 5000 Series (A API)

C++FA 5.1 PRACTICE MID-TERM EXAM

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Functions and Parameter Passing

1 Description of The Simpletron

C++ INTERVIEW QUESTIONS

LC-3 Assembly Language

Time Limit: X Flags: -std=gnu99 -w -O2 -fomitframe-pointer. Time Limit: X. Flags: -std=c++0x -w -O2 -fomit-frame-pointer - lm

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

Computer Organization and Architecture

VB.NET Programming Fundamentals

Building Java Programs


How To Write Portable Programs In C

MXwendler Javascript Interface Description Version 2.3

Chapter 4 OOPS WITH C++ Sahaj Computer Solutions

Chapter 5 Names, Bindings, Type Checking, and Scopes

Java Interview Questions and Answers

Programming with Data Structures

Lecture 2 Notes: Flow of Control

Functions Recursion. C++ functions. Declare/prototype. Define. Call. int myfunction (int ); int myfunction (int x){ int y = x*x; return y; }

Input and Interaction

The Little Man Computer

System Calls and Standard I/O

Coding Rules. Encoding the type of a function into the name (so-called Hungarian notation) is forbidden - it only confuses the programmer.

Informatica e Sistemi in Tempo Reale

Chapter 13 Storage classes

Lecture Notes on Linear Search

Stacks. Data Structures and Data Types. Collections

6. Standard Algorithms

Figure 1: Graphical example of a mergesort 1.

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Chapter 5 Instructor's Manual

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Lecture 2 Mathcad Basics

Contents. 9-1 Copyright (c) N. Afshartous

Review of Hashing: Integer Keys

Base Conversion written by Cathy Saxton

Comp 255Q - 1M: Computer Organization Lab #3 - Machine Language Programs for the PDP-8

5 Arrays and Pointers

Formal Languages and Automata Theory - Regular Expressions and Finite Automata -

public static void main(string[] args) { System.out.println("hello, world"); } }

Chapter One Introduction to Programming

GETTING STARTED WITH PROGRAMMABLE LOGIC DEVICES, THE 16V8 AND 20V8

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Chapter 5. Selection 5-1

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push)

CS1010 Programming Methodology A beginning in problem solving in Computer Science. Aaron Tan 20 July 2015

Introduction to Python

An Incomplete C++ Primer. University of Wyoming MA 5310

1. Use the class definition above to circle and identify the parts of code from the list given in parts a j.

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Transcription:

Phys4051: C Lectures Pointers and Address Operators Pointer to a Variable Function Calls: Passing by Value and Passing by Reference Pointer to an Array Pointers and Variables: Definition Variable: A variable refers to a memory location that contains a numerical value. Pointer A pointer refers to a memory location that contains an address. 1 2 Pointers: Operators (1) Address Operator: & Note: it looks identical to the bitewise AND operator but it is used in a completely different way! Returns the address of a variable Example: prt_v = & x; Pointers: Operators (2) Indirection Operator: * Note: it looks identical to the multiplication operator but it is used in a completely different way! Retrieves a value from the memory location the pointer points to. Example: *ptr_v = 77; 3 4 Pointer Declaration A pointer must be declared and the variable type it points to must be specified: Assigning an Address to a Pointer (1) An address is assigned to a pointer using the address operator: & short *aptr; //pointer declaration double *bptr; float* fptr; //same as float *fptr Example: prt_v = & x; 5 6 1

Assigning an Address to a Pointer (2) Pointer Usage with a Variable: Indirection Op. Example: short x = 33; short *aptr; //pointer declaration aptr = & x; x aptr Example: short x = 33; short *aptr; aptr = & x; *aptr = -123; x aptr //declare the ptr //ptr points to x //assign a value to x 33 5012-123 33 5012 5012 5014 5016 5018 5020 5012 5014 5016 5018 5020 (The memory addresses are arbitrarily chosen) 7 (The memory addresses are arbitrarily chosen) 8 Pointer Usage with a Variable: Pointers: Additional Comment The following two segments are equivalent in respect what they do to variable x : short x = 33; short *aptr; aptr = & x; *aptr = -123; short x = 33; x = -123; Pointers refer to an address which is almost always the address of another variable. An (arbitrary) address can be directly assigned to a pointer. Doing so makes the program less portable and can be very dangerous! Example: short *aptr = 0x300; *aptr = 0xff; //0x means HEX 9 10 Arrays and Pointers Arrays & Pointers: Pointer to the Zeroth Array Element Pointers are most often used in function calls and with arrays. Because pointers are so often used with arrays, a special pointer has been designated in C to point to the zeroth element in an array: the array name itself! Example 2a: float w[128]; float *w_ptr; w_ptr = & w[0]; Example 2b: float w[128]; float *w_ptr; w_ptr = w; 11 12 2

Pointer to the Zeroth Array Element: Summary Each time you declare an array, you also declare implicitly a pointer to the zeroth element! Arrays: Memory Allocation short x = 2; //declare & init. x short y[4]; //declare array y[] y[x] = 12345; *y = 4051; //where does y point to? x y[0] y[1] y[2] y[3] The name of this pointer is the name of the array! 13 2 4051 12345 5012 y 5014 5016 5018 5020 (The memory addresses are arbitrarily chosen) 14 Arrays: Memory Allocation: Pointer Math (1) Arrays: Memory Allocation: Pointer Math (2) short x = 2; short y[4]; y[x] = 12345; *y = 4051; //same as: y[0] = 4051; *(y+1) = 4052; y[0] y[1] y[2] y[3] x 2 4051 4052 12345 5012 5014 5016 5018 5020 (Addresses) y y+1 15 short x = 2; short y[4]; *y = 4051; //same as: y[0] = 4051; *(y+1) = 4052; //same as: y[1] = 4052; *(y+x) = 4053; //same as:? x y[0] y[1] y[2] y[3] 2 4051 4052 12345 4053 5012 5014 5016 5018 5020 (Addresses) y y+1 y+2 16 Arrays: Memory Allocation: Pointer Math (3) The following two segments are equivalent statements: Segment 3a: short x, y[ MAX], val; Segment 3b: short x, y[ MAX], val; Pointers When an array is passed to a function it is passed by REFERENCE, i.e., a pointer to the array is passed! Ex: short sar[ MAX ]; //declare array SortAr( sar, MAX ); //call function y[x] = val; *(y + x) = val; 17 18 3

Arrays and Function Calls: Example: Initialize an Array Write a function that will initialize an entire array, i.e., set each element to 0. void Init( double* ar, int n ) int i; for( i = 0; i < n ; i++) ar[i] = 0; //pntr. or arr? Pointers: Example 3 A) Write a function that returns the average of an array of type double. B) Write a program that uses above function. C) Change the program above to account for that the fact that we want to ignore the first 5 data points in the array when calculating the average. 19 20 Pointers: Example 3 A Pointers: Example 3 B double Ave( double* dar, int n ) int i; double dtot = 0; for( i = 0; i < n ; i++) dtot += dar[i]; //pntr. or arr? return( dtot/n); 21 double Ave( double* dar, int n ); double dave, dtemp[1000]; //lines of code to fill array dtemp // are omitted here... dave = Ave( dtemp, 1000); printf( %d, dave); // code for func. Ave() follows here 22 Pointers: Example 3 C Example 4: Function to Sort an Array (1): Problem double Ave( double* dar, int n ); double dave, dtemp[1000]; //lines of code to fill array dtemp // are omitted here... dave = Ave( dtemp + 5, 995); printf( %d, dave); // code for func. Ave() follows here 23 Assignment: Write a function that sorts the values contained in an array. 24 4

Example 4: Function to Sort an Array (2): Solution Pass arrays whenever possible by reference! (Also, no need for global arrays!) Passing an array by value takes a long time (and lots of space) because the computer has to make a copy of the array to pass it to the function. 25 Ex. 4: Function to Sort an Array (3): main #define MAX 10 void SortAr( short *volt, short n ); short i, sar[ MAX ]; for( i = 0; i < MAX; i++) sar[i] = rand(); printf("%d %d\n", i, sar[i] ); SortAr( sar, MAX ); // pass by ref for( i = 0; i < MAX; i++) printf("%d %d\n", i, sar[i] ); 26 Ex. 4: Function to Sort an Array (4): Sort Function V1 void SortAr( short *volt, short n ) short x, y, stemp; for( y = 0; y < n - 1; y++) for( x = 0; x < n - 1 - y; x++ ) if( volt[ x ] > volt[ x + 1] ) stemp = volt[x]; volt[x] = volt[x+1]; volt[x+1] = stemp; Ex. 4: Function to Sort an Array (5): Sort Function V2 void SortAr( short *volt, short n ) short x, y, stemp; for( y = 0; y < n - 1; y++) for( x = 0; x < n - 1 - y; x++ ) if( *(volt+x) > *(volt+x+1)) stemp = *(volt+x); *(volt+x) = *(volt+x+1); *(volt+x+1) = stemp; 27 28 Example: Uniqueness (1) You are given an (integer) array with N elements. Count how many of the values in this array are unique and copy the unique values from this first array into a second array. For example, if the first array contained: 8, 7, 7, 3, 8, 5, 3 then it has 4 unique entries and the second array should contain the following values: 8, 7, 3, 5. Example: Uniqueness Hints: To check for uniqueness, you must compare each element of the first array with every element of the second array. Specifically: If the second array already contains an entry identical to the one you are checking (in the first array) then go on and check the next element in the first array. If the second array does NOT contains an entry identical to the one you are checking (in the first array) then: copy the value from the first array to the end of the second array; increment the number of elements that the second array contains. 29 30 5

Pointers: Function Calls and Function Arguments Variables can be passed to a function (as function arguments) either: a) by value (as a copy of a local variable) b) by reference (by a pointer) Function Arguments: Passing by Value This is the method you have used so far in these examples. A (local) copy of the variable is passed to function. Changing the (passed) variable within the calling function has no effect on the (original) variable that was passed. 31 32 Ex. 1: Exchange Two Variables: By Value Ex. 1a: Exchange Two Variables (2): main Problem: a) Write a function Xchange that will exchange two variables if the first variable is greater than the second one. b) You are not allowed to use GLOBAL variables! 33 void Xchange_ByVal(short u, short v); short x = 10, y = 2; Xchange_ByVal(x, y); printf("x: %d ", x); printf("y: %d\n", y); 34 Ex. 1a: Exchange Two Variables (3): Function void Xchange_ByVal(short u, short v ) short stemp; if( u > v) stemp = v; v = u; u = stemp; printf("u: %d ", u); printf("v: %d\n", v); 35 Ex. 1a: Exchange Two Variables (4): Output Output: u: v: x: y: Conclusion: Works? (y/n) Why (not)? 36 6

Function Arguments: Passing by Reference Ex. 1b: Exchange Two Variables (5): By Reference Allows you to change the value of a variable which is not local to the function without having to make it global Pass a reference (a pointer) to the function which tells the function where to find that variable Note: (usually) you don t change the reference, you change only what the reference points to! 37 Solution: Pass the function arguments by reference! 38 Ex. 1b: Exchange Two Variables (6): main Ex. 1b: Exchange Two Variables (7): Function void Xchange_ByRef(short *u, short *v); short x = 10, y = 2; Xchange_ByRef(&x, &y); printf("x: %d ", x); printf("y: %d\n", y); void Xchange_ByRef(short *u, short *v ) short stemp; if( *u > *v) stemp = *v; *v = *u; *u = stemp; printf("u: %d ", *u); printf("v: %d\n", *v); 39 40 Ex. 1b: Exchange Two Variables (8): Output Output: u: v: x: y: Conclusion: Works? (y/n) Function Arguments and Pointers: Summary Passing (a Variable) by Value: Variable is local to function and, therefore, can not alter the original value. Passing (a Variable) by Reference Since a reference to the variable is passed, the original value can be accessed and altered. 41 42 7

Summary: Function Calls a) by Value Summary: Function Calls b) by Reference Passing a Variable by Value: Passing a Pointer by Value: Passing a Variable by Reference: Passing a Pointer by Refrerence: void FbyVal( int ); int y = 3; FbyVal( ); void FbyVal( int ); int x = 3; int* y = &x; FbyVal( ); void FbyRef( int* ); int y = 3; FbyRef( ); void FbyRef( int* ); int x = 3; int* y = &x; FbyRef( ); 43 44 8