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

Similar documents
CS61C : Machine Structures

CS61C : Machine Structures

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

CS61C Machine Structures. Lecture 5 C Structs & Memory Mangement. 1/27/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

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

How about them A s!! Go Oaktown!! CS61C - Machine Structures. Lecture 4 C Structures Memory Management Dan Garcia.

CS61C : Machine Structures

ECE 15B COMPUTER ORGANIZATION

CS61C : Machine Structures

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

review Pointers and arrays are virtually same C knows how to increment pointers C is an efficient language, with little protection

Reference slides! Garcia, Fall 2011 UCB! CS61C L04 Introduction to C (pt 2) (1)!

CS61C : Machine Structures

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

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?!

Has there been an update to ANSI C? Lecture #3 C Pointers Yes! It s called the C99 or C9x std

Review! * follows a pointer to its value! & gets the address of a variable! Pearce, Summer 2010 UCB! ! int x = 1000; Pearce, Summer 2010 UCB!

CS61C : Machine Structures

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

CS 61c: Great Ideas in Computer Architecture

Lectures 13 & 14. memory management

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

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

More C Pointer Dangers

C Arrays, Strings, More Pointers Instructor: Steven Ho

IT 252 Computer Organization and Architecture Introduction to the C Programming Language

CS61C : Machine Structures

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

Numbers: positional notation. CS61C Machine Structures. Faux Midterm Review Jaein Jeong Cheng Tien Ee. www-inst.eecs.berkeley.

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

Instructor: Randy H. Katz hbp://inst.eecs.berkeley.edu/~cs61c/fa13. Fall Lecture #4. Agenda

review Pointers and arrays are virtually same C knows how to increment pointers C is an efficient language, with little protection

CS61C : Machine Structures

Lecture 5: Outline. I. Multi- dimensional arrays II. Multi- level arrays III. Structures IV. Data alignment V. Linked Lists

Intro to C: Pointers and Arrays

Arrays and Memory Management

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Bernhard Boser & Randy Katz

Intermediate Programming, Spring 2017*

Agenda. Components of a Computer. Computer Memory Type Name Addr Value. Pointer Type. Pointers. CS 61C: Great Ideas in Computer Architecture

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz

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

Pointers, Arrays, Memory: AKA the cause of those Segfaults

CS61C : Machine Structures

CS 61C: Great Ideas in Computer Architecture Introduc)on to C, Part II

Functions:"" Breaking"large"computing"tasks"to" smaller"ones"

Arrays and Pointers in C. Alan L. Cox

CS 11 C track: lecture 5

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

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

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

Dynamic Data Structures. CSCI 112: Programming in C

Heap Arrays and Linked Lists. Steven R. Bagley

Physics 2660: Fundamentals of Scientific Computing. Lecture 3 Instructor: Prof. Chris Neu

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

CS61, Fall 2012 Section 2 Notes

Understanding Pointers

CS24 Week 2 Lecture 1

First of all, it is a variable, just like other variables you studied

Arrays, Pointers and Memory Management

Character Strings. String-copy Example

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

Agenda. Address vs. Value Consider memory to be a single huge array. Review. Pointer Syntax. Pointers 9/9/12

CS61C : Machine Structures

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

Pointers in C/C++ 1 Memory Addresses 2

CS 61C: Great Ideas in Computer Architecture Introduc)on to C, Part II. Control. Consider memory to be a single huge array

Review! Lecture 5 C Memory Management !

Lecture 2: C Programm

CS61C : Machine Structures

Lecture 10: Program Development versus Execution Environment

Systems Programming and Computer Architecture ( )

Processor. Lecture #2 Number Rep & Intro to C classic components of all computers Control Datapath Memory Input Output }

Lecture 7: Procedures and Program Execution Preview

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

Array Initialization

CS 222: Pointers and Manual Memory Management

Sir Syed University of Engineering and Technology. Computer Programming & Problem Solving ( CPPS ) Pointers. Chapter No 7

CS61C : Machine Structures

Number review... Lecture 3 Introduction to the C Programming Language (pt 1) Has there been an update to ANSI C?

Dynamic memory allocation (malloc)

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Topics Introduction to Microprocessors

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

Design and development of embedded systems for the Internet of Things (IoT) Fabio Angeletti Fabrizio Gattuso

EM108 Software Development for Engineers

CS 61C: Great Ideas in Computer Architecture Introduction to C, Part III

CS61C : Machine Structures

Lecture 8: Pointer Arithmetic (review) Endianness Functions and pointers

CS 61c: Great Ideas in Computer Architecture

CSE 333 Lecture 2 - arrays, memory, pointers

CS 102 Computer Architecture. Lecture 2: Introduction to C, Part I. Instructor: Sören Schwertfeger.

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

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

CS107, Lecture 9 C Generics Function Pointers

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

Memory, Data, & Addressing II

ECE 250 / CS 250 Computer Architecture. C to Binary: Memory & Data Representations. Benjamin Lee

C: Introduction, Pointers Instructors: Steven Ho, Nick Riasanovsky

Pointers and File Handling

Pointers and Arrays 1

Transcription:

CS61C L4 C Pointers (1) inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #4 C Strings, Arrays, & Malloc Albert Chae Instructor 2008-06-26 Review: C Strings A string in C is just an array of characters. char string[] = "abc"; Strings are ended by 0 byte (null terminator Value as int, 0 Value as char, '\0' Programmer manually manages memory for strings. CS61C L4 C Pointers (2) Review: Arrays vs. Pointers Review: Arrays vs. Pointers Arrays are (almost) identical to pointers char *str_ptr and char str_array[] are nearly identical They differ in very subtle ways: - Incrementing str_array++; // ILLEGAL - declaration of filled arrays int *int_array = 1,2,3; // ILLEGAL Key Difference: An array variable is a constant pointer to the first element. An array parameter can be declared as an array or a pointer; an array argument can be passed as a pointer. int strlen(char s[]) int n = 0; while (s[n]!= 0) n++; return n; Could be written: while (s[n]) int strlen(char *s) int n = 0; while (s[n]!= 0) n++; return n; CS61C L4 C Pointers (3) CS61C L4 C Pointers (4) Review: Pointer Arithmetic Since a pointer is just a mem address, we can add to it to traverse an array. p+1 returns a ptr to the next array elt. *p++ vs (*p)++ x = *p++ x = *p ; p = p + 1; x = (*p)++ x = *p ; *p = *p + 1; What if we have an array of large structs (objects) C takes care of it: In reality, p+1 doesn t add 1 to the memory address, it adds the size of the (type of) array element. Pointer Arithmetic Summary x = *(p+1) x = *(p+1) ; x = *p+1 x = (*p) + 1 ; x = (*p)++ x = *p ; *p = *p + 1; x = *p++ (*p++) *(p)++ *(p++) x = *p ; p = p + 1; x = *++p p = p + 1 ; x = *p ; Lesson Using anything but the standard *p++, (*p)++ causes more problems than it solves! P. 53 is a precedence table if you ever have to deal with this CS61C L4 C Pointers (5) CS61C L4 C Pointers (6)

CS61C L4 C Pointers (7) C String Standard Functions Pointers to pointers (1/4) review int strlen(char *string); compute the length of string int strcmp(char *str1, char *str2); return 0 if str1 and str2 are identical (how is this different from str1 == str2) char *strcpy(char *dst, char *src); copy the contents of string src to the memory at dst. The caller must ensure that dst has enough memory to hold the data to be copied. Sometimes you want to have a procedure increment a variable What gets printed void AddOne(int x) x = x + 1; int y = 5; AddOne( y); printf( y = %d\n, y); y = 5 CS61C L4 C Pointers (8) Pointers to pointers (2/4) review Pointers to pointers (3/4) Solved by passing in a pointer to our subroutine. Now what gets printed But what if what you want changed is a pointer What gets printed void AddOne(int *p) *p = *p + 1; y = 6 void IncrementPtr(int *p) p = p + 1; *q = 50 A q int y = 5; AddOne(&y); printf( y = %d\n, y); int A[3] = 50, 60, 70; int *q = A; IncrementPtr( q); printf( *q = %d\n, *q); 50 60 70 CS61C L4 C Pointers (9) CS61C L4 C Pointers (10) Pointers to pointers (4/4) Solution! Pass a pointer to a pointer, called a handle, declared as **h Now what gets printed void IncrementPtr(int **h) *h = *h + 1; int A[3] = 50, 60, 70; int *q = A; IncrementPtr(&q); printf( *q = %d\n, *q); *q = 60 A q q 50 60 70 Dynamic Memory Allocation (1/3) Recall that we can make ptrs point to something that already exists Newly allocated memory C has operator sizeof() which gives size in bytes (of type or variable) Assume size of objects can be misleading & is bad style, so use sizeof(type) Many years ago an int was 16 bits, and programs assumed it was 2 bytes CS61C L4 C Pointers (11) CS61C L4 C Pointers (12)

CS61C L4 C Pointers (13) Dynamic Memory Allocation (2/3) To allocate room for something new to point to, use malloc() (with the help of a typecast and sizeof): ptr = (int *) malloc (sizeof(int)); Now, ptr points to a space somewhere in memory of size (sizeof(int)) in bytes. (int *) simply tells the compiler what will go into that space (called a typecast). malloc is almost never used for 1 var ptr = (int *) malloc (n*sizeof(int)); This allocates an array of n integers. Dynamic Memory Allocation (3/3) Once malloc() is called, the memory location contains garbage, so don t use it until you ve set its value. When finished using dynamically allocated space, we must dynamically free it: free(ptr); Use this command to clean up. CS61C L4 C Pointers (14) Peer Instruction 1 Peer Instruction 2 What will y contain What is in foo and bar at the end of this program int main(int argc, char** argv) int y, *z; y = 4; z = &y; y = *z + 9; return 0; int main(int argc, char** argv) int foo, *bar, **baz, quux; bar = &quux; foo = 4; baz = &bar; **baz = 13; bar = &foo; **baz = 9; return 0; CS61C L4 C Pointers (15) CS61C L4 C Pointers (16) Administrivia Homework submission Guide on website, as well as within hw spec You can submit as many times as you like, we will only grade the latest one. Upcoming due dates HW0 out by tomorrow (sorry for delay) - Due 7/1 in lab or to my office - Picture + signed agreement to academic honesty policy Quiz 1 due Friday 6/27 HW1 due Monday 6/30 - Start today! Quiz 2 due Tuesday 7/1 HW2 due Saturday 7/5, should be out by end of this week Administrivia No Office Hours today (but I ll be in and out of lab) Waitlist should be resolved Newsgroup (details on website) CS61C L4 C Pointers (17) CS61C L4 C Pointers (18)

CS61C L4 C Pointers (19) Binky Pointer Video (thanks to NP @ SU) C structures : Overview A struct is a data structure composed for simpler data types. Like a class in Java/C++ but without methods or inheritance. struct point int x; int y; ; void PrintPoint(struct point p) printf( (%d,%d), p.x, p.y); CS61C L4 C Pointers (20) C structures: Pointers to them How big are structs The C arrow operator (->) dereferences and extracts a structure field with a single operator. The following are equivalent: struct point *p; printf( x is %d\n, (*p).x); printf( x is %d\n, p->x); Recall C operator sizeof() which gives size in bytes (of type or variable) How big is sizeof(p) struct p char x; int y; ; 5 bytes 8 bytes Compiler may word align integer y CS61C L4 C Pointers (21) CS61C L4 C Pointers (22) Let s look at an example of using structures, pointers, malloc(), and free() to implement a linked list of strings. struct Node char *value; struct Node *next; ; typedef struct Node *List; /* Create a new (empty) list */ List ListNew(void) return ; CS61C L4 C Pointers (23) CS61C L4 C Pointers (24)

CS61C L4 C Pointers (25) CS61C L4 C Pointers (26) CS61C L4 C Pointers (27) CS61C L4 C Pointers (28) Peer Instruction CS61C L4 C Pointers (29) Which are guaranteed to print out 5 I: main() int *a-ptr; *a-ptr = 5; printf( %d, *a-ptr); II: main() int *p, a = 5; p = &a;... /* code; a & p NEVER on LHS of = */ printf( %d, a); III: main() int *ptr; ptr = (int *) malloc (sizeof(int)); *ptr = 5; printf( %d, *ptr); CS61C L4 C Pointers (30) I II III 1: - - - 2: - - YES 3: - YES - 4: - YES YES 5: YES - - 6: YES - YES 7: YES YES - 8: YES YES YES

CS61C L4 C Pointers (31) Peer Instruction int main(void) int A[] = 5,10; int *p = A; 5 10 A[1] A[0] printf( %u %d %d %d\n,p,*p,a[0],a[1]); p = p + 1; printf( %u %d %d %d\n,p,*p,a[0],a[1]); *p = *p + 1; printf( %u %d %d %d\n,p,*p,a[0],a[1]); If the first printf outputs 100 5 5 10, what will the other two printf output 1: 101 10 5 10 then 101 11 5 11 2: 104 10 5 10 then 104 11 5 11 3: 101 <other> 5 10 then 101 <3-others> 4: 104 <other> 5 10 then 104 <3-others> 5: One of the two printfs causes an ERROR 6: I surrender! p Summary Use handles to change pointers Create abstractions with structures Dynamically allocated heap memory must be manually deallocated in C. Use malloc() and free() to allocate and deallocate memory from heap. CS61C L4 C Pointers (32)