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

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

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

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

Programming in C. Pointers and Arrays

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

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

POINTER AND ARRAY SUNU WIBIRAMA

Intro to C: Pointers and Arrays

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

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

Arrays and Pointers. CSE 2031 Fall November 11, 2013

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

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

Intermediate Programming, Spring 2017*

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

Arrays, Strings, & Pointers

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

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

Pointers, Dynamic Data, and Reference Types

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

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

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

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

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

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

Binghamton University. CS-211 Fall Pointers

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

MYcsvtu Notes LECTURE 34. POINTERS

CS 61c: Great Ideas in Computer Architecture

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

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

Pointers and scanf() Steven R. Bagley

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

ECE 15B COMPUTER ORGANIZATION

COMP 2355 Introduction to Systems Programming

Character Strings. String-copy Example

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

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

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).

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

Introduction to C. Ayush Dubey. Cornell CS 4411, August 31, Geared toward programmers

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers

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

a data type is Types

Procedures, Parameters, Values and Variables. Steven R. Bagley

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

Arrays, Pointers and Memory Management

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

Kurt Schmidt. October 30, 2018

C++ for Java Programmers

Lesson #8. Structures Linked Lists Command Line Arguments

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

Course organization. Course introduction ( Week 1)

CS61C : Machine Structures

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

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

Chapter 16. Pointers and Arrays. Address vs. Value. Another Need for Addresses

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

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

CS61C Machine Structures. Lecture 3 Introduction to the C Programming Language. 1/23/2006 John Wawrzynek. www-inst.eecs.berkeley.

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

Introduction to C. Zhiyuan Teo. Cornell CS 4411, August 26, Geared toward programmers

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

Procedural programming with C

Lectures 5-6: Introduction to C

Subject: Fundamental of Computer Programming 2068

Pointers. Pointers. Pointers (cont) CS 217

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

Arrays and Pointers in C. Alan L. Cox

ELEC 377 C Programming Tutorial. ELEC Operating Systems

PRINCIPLES OF OPERATING SYSTEMS

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

Lecture 04 Introduction to pointers

Dynamic memory allocation (malloc)

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

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

Arrays and Pointers (part 1)

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

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

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

Pointers. Pointer References

CS 261 Fall Mike Lam, Professor. Structs and I/O

Topics Introduction to Microprocessors

EL2310 Scientific Programming

CMSC202 Computer Science II for Majors

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

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

Compiling and Running a C Program in Unix

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

Week 5, continued. This is CS50. Harvard University. Fall Cheng Gong

Pointers and Arrays 1

CSE 333 Lecture 2 - arrays, memory, pointers

Arrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size]

CS 241 Data Organization Pointers and Arrays

Lecture 2, September 4

BITG 1113: POINTER LECTURE 12

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

Variables, Pointers, and Arrays

Principles of C and Memory Management

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

Transcription:

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

TOPICS TODAY Project 5 Pointer Basics Pointers and Arrays Pointers and Strings

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; }

POINTERS & STRINGS

Strings revisited Recall that a string is represented as an array of characters terminated with a null (\0) character. As we ve seen, arrays and pointers are closely related. A string constant may be declared as either as in char[ ] or char * char hello[ ] = Hello Bobby ; or (almost) equivalently char *hi = Hello Bob ; A typedef could also be used to simplify coding typedef char* STRING; STRING hi = Hello Bob ;

Arrays of Pointers Since a pointer is a variable type, we can create an array of pointers just like we can create any array of any other type. Although the pointers may point to any type, the most common use of an array of pointers is an array of char* to create an array of strings.

Boy s Names A common use of an array of pointers is to create an array of strings. The declaration below creates an initialized array of strings (char *) for some boys names. The diagram below illustrates the memory configuration. char *name[] = { Bobby, Jim, Harold }; name: 0 1 2 B o b b y \0 J i m \0 H a r o l d \0

Command Line Arguments Command line arguments:./a.out breakfast lunch dinner These arguments are passed to your program as parameters to main. int main( int argc, char *argv[ ] ) argc is the number of command line arguments argv is an array of argc strings argv[0]is always the name of your executable program. The rest of argv[] are the remaining strings on the command line.

Command Line Arguments (2) Example, with this command at the Linux prompt: we get myprog hello world 42 argc = 4 argv[0] = "myprog" argv[1] = "hello" argv[2] = "world" argv[3] = "42" Note: argv[3] is a string NOT an integer. Convert using atoi(): int answer = atoi( argv[3] );

NEXT TIME Advanced Pointers