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

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

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

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

Programming in C. Pointers and Arrays

POINTER AND ARRAY SUNU WIBIRAMA

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING PREVIEW SLIDES 14, SPRING 2013

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

Intro to C: Pointers and Arrays

Intermediate Programming, Spring 2017*

CS 61C: Great Ideas in Computer Architecture C Pointers. Instructors: Vladimir Stojanovic & Nicholas Weaver

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

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

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

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

HW1 due Monday by 9:30am Assignment online, submission details to come

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings

ECE 15B COMPUTER ORGANIZATION

MYcsvtu Notes LECTURE 34. POINTERS

NEXT SET OF SLIDES FROM DENNIS FREY S FALL 2011 CMSC313.

Pointers, Dynamic Data, and Reference Types

Announcements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1

Character Strings. String-copy Example

CS 61c: Great Ideas in Computer Architecture

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

Arrays, Strings, & Pointers

a data type is Types

Midterm Examination # 2 Wednesday, March 18, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER:

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

A function is a named piece of code that performs a specific task. Sometimes functions are called methods, procedures, or subroutines (like in LC-3).

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

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

Procedural programming with C

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

Subject: Fundamental of Computer Programming 2068

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

Arrays, Pointers and Memory Management

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

CSCI-1200 Data Structures Fall 2017 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

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

Binghamton University. CS-211 Fall Pointers

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

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

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

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

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

Compiling and Running a C Program in Unix

Lectures 5-6: Introduction to C

BITG 1113: POINTER LECTURE 12

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

Arrays and Pointers. CSE 2031 Fall November 11, 2013

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

Midterm Examination # 2 Wednesday, March 19, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER:

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

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

Introduction to C. Sean Ogden. Cornell CS 4411, August 30, Geared toward programmers

Class Information ANNOUCEMENTS

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-1200 Data Structures Fall 2018 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

Two s Complement Review. Two s Complement Review. Agenda. Agenda 6/21/2011

Variation of Pointers

REFERENCES, POINTERS AND STRUCTS

Computer Systems Principles. C Pointers

MIDTERM TEST EESC 2031 Software Tools June 13, Last Name: First Name: Student ID: EECS user name: TIME LIMIT: 110 minutes

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

Complex data types Structures Defined types Structures and functions Structures and pointers (Very) brief introduction to the STL

Array. Arrays. Declaring Arrays. Using Arrays

Reference slides! C Strings! A string in C is just an array of characters.!!!char string[] = "abc";! How do you tell how long a string is?!

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

CMSC 202. Pointers Dynamic Memory Allocation

CMSC202 Computer Science II for Majors

SYSC 2006 C Winter 2012

Principles of C and Memory Management

Principles of C and Memory Management

CIS 190: C/C++ Programming. Lecture 2 Pointers and More

Scheme G. Sample Test Paper-I. Course Name : Computer Engineering Group Course Code : CO/CD/CM/CW/IF Semester : Second Subject Tile : Programming in C

CSCI-1200 Data Structures Spring 2017 Lecture 5 Pointers, Arrays, Pointer Arithmetic

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

EL2310 Scientific Programming

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

CS61C Machine Structures. Lecture 4 C Structs & Memory Management. 9/5/2007 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

C Pointers. 6th April 2017 Giulio Picierro

C Programming Language: C ADTs, 2d Dynamic Allocation. Math 230 Assembly Language Programming (Computer Organization) Thursday Jan 31, 2008

CMPT 115. C tutorial for students who took 111 in Java. University of Saskatchewan. Mark G. Eramian, Ian McQuillan CMPT 115 1/32

C++ for Java Programmers

Pointers and Arrays 1

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

2/28/2018. Overview. The C Programming Language Part 4. Pointers. Pointers. Pointers. Pointers

The C Programming Language Part 4. (with material from Dr. Bin Ren, William & Mary Computer Science, and

Lecture 05 POINTERS 1

C Programming Review CSC 4320/6320

Lecture 04 FUNCTIONS AND ARRAYS

CS Introduction to Programming Midterm Exam #2 - Prof. Reed Fall 2015

Number Review. Lecture #3 More C intro, C Strings, Arrays, & Malloc Variables. Clarification about counting down

CS 11 C track: lecture 5

Variables, Pointers, and Arrays

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CS61C : Machine Structures

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

Week 7 Part I. Kyle Dewey. Monday, August 6, 12

Transcription:

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

TOPICS TODAY Reminder: MIDTERM EXAM on THURSDAY Pointer Basics Pointers & Arrays Pointers & Strings Pointers & Structs

POINTER BASICS

Java Reference In Java, the name of an object is a reference to that object. Here ford is a reference to a Truck object. It contains the memory address at which the Truck object is stored. Truck ford = new Truck( ); The syntax for using the reference is pretty simple. Just use the dot notation. ford.start( ); ford.drive( 23 ); ford.turn (LEFT);

What is a pointer? pointer = memory address + type C pointers vs Java references A pointer can contain the memory address of any variable type (Java references only refer to objects) A primitive (int, char, float) An array A struct or union Dynamically allocated memory Another pointer A function There s a lot of syntax required to create and use pointers

Why Pointers? They allow you to refer to large data structures in a compact way They facilitate sharing between different parts of programs They make it possible to get new memory dynamically as your program is running They make it easy to represent relationships among data items.

Pointer Caution Undisciplined use can be confusing and thus the source of subtle, hard-to-find bugs. Program crashes Memory leaks Unpredictable results About as "dangerous" as memory addresses in assembly language programming.

C Pointer Variables General declaration of a pointer type *nameofpointer ; Example: int *ptr1 ; Notes: * = dereference "if I dereference ptr1, I have an int" name of pointer variable should indicate it is a pointer here x is pointer, y is NOT: int *x, y;

Pointer Operators * = dereference The * operator is used to define pointer variables and to dereference a pointer. Dereferencing a pointer means to use the value of the pointee. & = address of The & operator gives the address of a variable. Recall the use of & in scanf( )

Pointer Examples int x = 1, y = 2 ; int *ip ; /* pointer to int */ ip = &x ; y = *ip ; *ip = 0 ; *ip = *ip + 10 ; *ip += 1 ; (*ip)++ ; ip++ ;

Pointer and Variable types The type of a pointer and its pointee must match int a = 42; int *ip; double d = 6.34; double *dp; ip = &a; /* ok -- types match */ dp = &d; /* ok */ ip = &d; /* compiler error -- type mismatch */ dp = &a; /* compiler error */

More Pointer Code int a = 1, *ptr1; ptr1 = &a ; printf("a = %d, &a = %p, ptr1 = %p, *ptr1 = %d\n", a, &a, ptr1, *ptr1) ; *ptr1 = 35 ; printf( a = %d, &a = %p, ptr1 = %p, *ptr1 = %d\n", a, &a, ptr1, *ptr1) ;

NULL NULL is a special value which may be assigned to a pointer NULL indicates that a pointer points to nothing Often used when pointers are declared int *pint = NULL; Used as return value to indicate failure int *myptr; myptr = myfunction( ); if (myptr == NULL){ /* something bad happened */ } Dereferencing a pointer whose value is NULL will result in program termination.

Pointers and Function Arguments Since C passes all primitive function arguments by value. /* version 1 of swap */ void swap (int a, int b) { int temp; temp = a; a = b; b = temp; } /* calling swap from somewhere in main() */ int x = 42, y = 17; swap( x, y ); printf( %d, %d\n, x, y); // what does this print?

A better swap( ) /* pointer version of swap */ void swap (int *px, int *py) { int temp; temp = *px; *px = *py; *py = temp; } /* calling swap from somewhere in main( ) */ int x = 42, y = 17; swap( &x, &y ); printf( %d, %d\n, x, y); // what does this print?

More Pointer Function Parameters Passing the address of variable(s) to a function can be used to have a function return multiple values. The pointer arguments point to variables in the calling code which are changed ( returned ) by the function.

ConvertTime.c void converttime (int time, int *phours, int *pmins) { *phours = time / 60; *pmins = time % 60; } int main( ) { int time, hours, minutes; printf("enter a time duration in minutes: "); scanf ("%d", &time); converttime (time, &hours, &minutes); printf("hh:mm format: %d:%02d\n", hours, minutes); return 0; }

An Exercise What is the output from this code? void myfunction (int a, int *b) { a = 7 ; *b = a ; b = &a ; *b = 4 ; printf("%d, %d\n", a, *b) ; } int main() { int m = 3, n = 5; myfunction(m, &n) ; printf("%d, %d\n", m, n) ; return 0; }

Pointers to struct /* define a struct for related student data */ typedef struct student { char name[50]; char major [20]; double gpa; } STUDENT; STUDENT bob = {"Bob Smith", "Math", 3.77}; STUDENT sally = {"Sally", "CSEE", 4.0}; /* pstudent is a "pointer to struct student" */ STUDENT *pstudent; /* make pstudent point to bob */ pstudent = &bob;

Pointers to struct (2) /* pstudent is a "pointer to struct student" */ STUDENT *pstudent; /* make pstudent point to bob */ pstudent = &bob; printf ("Bob's name: %s\n", (*pstudent).name); printf ("Bob's gpa : %f\n", (*pstudent).gpa); /* use -> to access the members */ pstudent = &sally; printf ("Sally's name: %s\n", pstudent->name); printf ("Sally's gpa: %f\n", pstudent->gpa);

Pointer to struct for functions void printstudent(student *studentp) { printf( Name : %s\n, studentp->name); printf( Major: %s\n, studentp->major); printf( GPA : %4.2f, studentp->gpa); } Passing a pointer to a struct to a function is more efficient than passing the struct itself. Why is this true?

POINTERS & ARRAYS

Pointers and Arrays In C, there is a strong relationship between pointers and arrays. The declaration int a[10]; defines an array of 10 integers. The declaration int *p; defines p as a pointer to an int. The assignment p = a; makes p an alias for the array and sets p to point to the first element of the array. (We could also write p = &a[0];) We can now reference members of the array using either a or p a[4] =9; p[3] = 7; int x = p[6] + a[4] * 2;

More Pointers and Arrays The name of an array is equivalent to a pointer to the first element of the array and vice-versa. Therefore, if a is the name of an array, the expression a[ i ] is equivalent to *(a + i). It follows then that &a[ i ] and (a + i) are also equivalent. Both represent the address of the i-th element beyond a. On the other hand, if p is a pointer, then it may be used with a subscript as if it were the name of an array. p[ i ] is identical to *(p + i) In short, an array-and-index expression is equivalent to a pointer-andoffset expression and vice-versa.

So, what s the difference? If the name of an array is synonymous with a pointer to the first element of the array, then what s the difference between an array name and a pointer? An array name can only point to the first element of its array. It can never point to anything else. A pointer may be changed to point to any variable or array of the appropriate type

Array Name vs Pointer int g, grades[ ] = {10, 20, 30, 40 }, mygrade = 100, yourgrade = 85, *pgrade; /* grades can be (and usually is) used as array name */ for (g = 0; g < 4; g++) printf( %d\n grades[g]); /* grades can be used as a pointer to its array if it doesn t change*/ for (g = 0; g < 4; g++) printf( %d\n *(grades + g); /* but grades can t point anywhere else */ grades = &mygrade; /* compiler error */ /* pgrades can be an alias for grades and used like an array name */ pgrades = grades; /* or pgrades = &grades[0]; */ for( g = 0; g < 4; g++) printf( %d\n, pgrades[g]); /* pgrades can be an alias for grades and be used like a pointer that changes */ for (g = 0; g < 4; g++) printf( %d\n *pgrades++); /* BUT, pgrades can point to something else other than the grades array */ pgrades = &mygrade; printf( %d\n, *pgrades); pgrades = &yourgrade; printf( %d\n, *pgrades);

More Pointers & Arrays If p points to a particular element of an array, then p + 1 points to the next element of the array and p + n points n elements after p. The meaning a adding 1 to a pointer is that p + 1 points to the next element in the array, REGARDLESS of the type of the array.

Pointer Arithmetic If p is an alias for an array of ints, then p[ k ] is the k-th int and so is *(p + k). If p is an alias for an array of doubles, then p[ k ] is the k-th double and so is *(p + k). Adding a constant, k, to a pointer (or array name) actually adds k * sizeof(pointer type) to the value of the pointer. This is one important reason why the type of a pointer must be specified when it s defined.

Pointer Gotcha But what if p isn t the alias of an array? Consider this code. int a = 42; int *p = &a; printf( %d\n, *p); // prints 42 ++p; // to what does p point now? printf( %d\n, *p); // what gets printed?

Printing an Array The code below shows how to use a parameter array name as a pointer. void printgrades( int grades[ ], int size ) { int i; for (i = 0; i < size; i++) printf( %d\n, *grades ); ++grades; } What about this prototype? void printgrades( int *grades, int size );

Passing Arrays Arrays are passed by reference (its address is passed by value): int sumarray( int A[], int size) ; is equivalent to int sumarray( int *A, int size) ; Use A as an array name or as a pointer. The compiler always sees A as a pointer. In fact, any error messages produced will refer to A as an int *

sumarray int sumarray( int A[ ], int size) { } int k, sum = 0; for (k = 0; k < size; k++) sum += A[ k ]; return sum;

sumarray (2) int sumarray( int A[ ], int size) { int k, sum = 0; for (k = 0; k < size; k++) sum += *(A + k); return sum; } int sumarray( int A[ ], int size) { int k, sum = 0; for (k = 0; k < size; k++) } sum += *A; ++A; } return sum; }