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

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

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

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

CS61C : Machine Structures

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

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

More C Pointer Dangers

CS 61c: Great Ideas in Computer Architecture

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

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 Pointers. Instructors: Vladimir Stojanovic & Nicholas Weaver

ECE 15B COMPUTER ORGANIZATION

CS61C : Machine Structures

C Arrays, Strings, More Pointers Instructor: Steven Ho

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

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

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

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

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

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. Bernhard Boser & Randy Katz

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

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

CS61C : Machine Structures

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

CS61C : Machine Structures

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

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/

CS61C : Machine Structures

Intro to C: Pointers and Arrays

CS61C : Machine Structures

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

Arrays and Memory Management

Arrays and Pointers in C. Alan L. Cox

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

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

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

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

CS 61C: Great Ideas in Computer Architecture Strings and Func.ons. Anything can be represented as a number, i.e., data or instruc\ons

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

CS61C : Machine Structures

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

Lecture 2: C Programm

Instructor: Randy H. Katz hap://inst.eecs.berkeley.edu/~cs61c/fa13. Fall Lecture #7. Warehouse Scale Computer

CS61C : Machine Structures

CS61C : Machine Structures

Topics Introduction to Microprocessors

CS61C : Machine Structures

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

CS61C : Machine Structures

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

CS 61c: Great Ideas in Computer Architecture

CS 61C: Great Ideas in Computer Architecture (Machine Structures) Introduc)on to C (Part I) We are here!

CS 61C: Great Ideas in Computer Architecture Func%ons and Numbers

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

Intermediate Programming, Spring 2017*

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

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

CS 61C: Great Ideas in Computer Architecture Introduc=on to C, Part I. We are here!

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

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

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

Lecture #6 Intro MIPS; Load & Store

Multidimension array, array of strings

CS 61C: Great Ideas in Computer Architecture Lecture 15: Caches, Part 2

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

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

CS 61C: Great Ideas in Computer Architecture. Lecture 2: Numbers & C Language. Krste Asanović & Randy Katz

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

Array Initialization

Arrays and Pointers (part 1)

Arrays and Pointers. CSE 2031 Fall November 11, 2013

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

So far, system calls have had easy syntax. Integer, character string, and structure arguments.

Outline. Pointers arithme.c and others Func.ons & pointers

Homework #3 CS2255 Fall 2012

CS 61C: Great Ideas in Computer Architecture (Machine Structures) Introduc)on to Machine Language

Memory, Arrays & Pointers

Arrays and Pointers (part 1)

Agenda. CS 61C: Great Ideas in Computer Architecture. Lecture 2: Numbers & C Language 8/29/17. Recap: Binary Number Conversion

Lecture 04 Introduction to pointers

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

C++ for Java Programmers

Lectures 5-6: Introduction to C

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

CS 449 Lecture 3. Variables in memory. Dr. Jack Lange. int x = 4;

9/9/12. New- School Machine Structures (It s a bit more complicated!) CS 61C: Great Ideas in Computer Architecture IntroducMon to Machine Language

CS 61C: Great Ideas in Computer Architecture (Machine Structures) More MIPS Machine Language

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

Principles of Programming Pointers, Dynamic Memory Allocation, Character Arrays, and Buffer Overruns

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

Lectures 13 & 14. memory management

CS 61C: Great Ideas in Computer Architecture Lecture 2: Introduction to C, Part I

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

CS61C : Machine Structures

Under the Hood: Data Representations, Memory and Bit Operations. Computer Science 104 Lecture 3

CS 0449 Sample Midterm

CS 61C: Great Ideas in Computer Architecture Introduction to C

Transcription:

CS 61C: Great Ideas in Computer Architecture Introduc)on to C, Part II Instructor: Randy H. Katz hbp://inst.eecs.berkeley.edu/~cs61c/fa13 9/10/13 Fall 2013 - - Lecture #4 1 Agenda Pointers and Arrays Administrivia Pointer arithmeqc Arrays vs. pointers Technology Break Pointer Problems CriQcisms of C And in Conclusion, 9/10/13 Fall 2013 - - Lecture #4 2 1

Pointers and Arrays Administrivia Pointer arithmeqc Arrays vs. pointers Technology Break Pointer Problems CriQcisms of C And in Conclusion, Agenda 9/10/13 Fall 2013 - - Lecture #4 3 New- School Machine Structures (It s a bit more complicated!) Parallel Requests Assigned to computer e.g., Search Katz Parallel Threads Assigned to core e.g., Lookup, Ads So0ware Harness Parallelism & Achieve High Performance Parallel InstrucQons >1 instrucqon @ one Qme e.g., 5 pipelined instrucqons Parallel Data >1 data item @ one Qme e.g., Add of 4 pairs of words Hardware descripqons All gates @ one Qme Programming Languages Hardware Today s Lecture Warehouse Scale Computer Core Memory Input/Output InstrucQon Unit(s) Cache Memory Core 9/10/13 Fall 2013 - - Lecture #4 4 Computer (Cache) Core FuncQonal Unit(s) A 0 +B 0 A 1 +B 1 A 2 +B 2 A 3 +B 3 Smart Phone Logic Gates 2

Big Idea #1: Levels of RepresentaQon/ InterpretaQon Machine Interpreta4on High Level Language Program (e.g., C) Compiler Assembly Language Program (e.g., MIPS) Assembler Machine Language Program (MIPS) Hardware Architecture DescripCon (e.g., block diagrams) Architecture Implementa4on Logic Circuit DescripCon (Circuit SchemaCc Diagrams) temp = v[k]; v[k] = v[k+1]; v[k+1] = temp; lw $t0, 0($2) lw $t1, 4($2) sw $t1, 0($2) sw $t0, 4($2) We are here! Anything can be represented as a number, i.e., data or instrucqons 0000 1001 1100 0110 1010 1111 0101 1000 1010 1111 0101 1000 0000 1001 1100 0110 1100 0110 1010 1111 0101 1000 0000 1001 0101 1000 0000 1001 1100 0110 1010 1111! 9/10/13 Fall 2013 - - Lecture #4 5 Pointer Review int *x;! Tells compiler that variable x is address of an int! x = &y;! Tells compiler to assign address of y to x! & called the address operator in this context! z = *x;! Tells compiler to assign value at address in x to z! * called the dereference operator in this context! 9/10/13 Fall 2013 - - Lecture #4 6 3

Pointer Review How to change a variable pointed to? Use the dereference operator * on lek of assignment operator = p x 3 *p = 5; p x 5 9/10/13 Fall 2013 - - Lecture #4 7 Pointers and Parameter Passing Java and C pass parameters by value Procedure/funcQon/method gets a copy of the parameter, so changing the copy cannot change the original void addone (int x) { " x = x + 1; " int y = 3;" addone(y);" y remains equal to 3 9/10/13 Fall 2013 - - Lecture #4 8 4

Pointers and Parameter Passing How can we get a funcqon to change the value held in a variable? void addone (int *p) { "*p = *p + 1; " int y = 3;" addone(&y);" y is now equal to 4 9/10/13 Fall 2013 - - Lecture #4 9 C Pointer Dangers Declaring a pointer just allocates space to hold the pointer it does not allocate the thing being pointed to! Local variables in C are not iniqalized, they may contain anything (aka garbage ) What does the following code do? void f() { int *ptr; *ptr = 5; 9/10/13 Fall 2013 - - Lecture #4 10 5

struct Point { int x; ; int y; Point p1; Point p2; Point *paddr; Pointers and Structures /* dot notation */ int h = p1.x; p2.y = p1.y; /* arrow notation */ int h = paddr->x; int h = (*paddr).x; /* This works too */ p1 = p2; 9/10/13 Fall 2013 - - Lecture #4 11 How many logic and syntax errors? 1 2 3 void main(); { int *p, x=5, y; // init y = *(p = &x) + 1; int z; flip-sign(p); printf("x=%d,y=%d,p=%d\n",x,y,p); flip-sign(int *n){*n = -(*n) 9/10/13 Fall 2013 - - Lecture #4 12 6

Peer InstrucQon Answer #insert <stdio.h> void main(); { //int main(void){ int *p, x=5, y; // init y = *(p = &x) + 1; int z; flip-sign(p); printf("x=%d,y=%d,p=%d\n",x,y,*p); flip-sign(int *n){*n = -(*n); // return (0); More than four syntax + logic errors in this C code 9/10/13 Fall 2013 - - Lecture #4 13 What is output aker correct errors? x=5,y=6,p=-5 x=-5,y=6,p=-5! x=-5,y=4,p=-5! void main(); { int *p, x=5, y; // init int z; y = *(p = &x) + 1; flip_sign(p); printf("x=%d,y=%d,p=%d\n", x,y,*p); flip_sign(int *n) {*n = -(*n); 9/10/13 Fall 2013 - - Lecture #4 14 7

What is output aker correct errors? x=5,y=6,p=-5 x=-5,y=6,p=-5! x=-5,y=4,p=-5! void main(); { int *p, x=5, y; // init int z; y = *(p = &x) + 1; flip_sign(p); printf("x=%d,y=%d,p=%d\n", x,y,*p); flip_sign(int *n) {*n = -(*n); 9/10/13 Fall 2013 - - Lecture #4 15 Arrays (1/5) DeclaraQon: int ar[2]; declares a 2- element integer array: just a block of memory int ar[] = {795, 635; declares and iniqalizes a 2- element integer array Accessing elements: ar[num] returns the num th element 9/10/13 Fall 2011 - - Lecture #4 16 8

Arrays (2/5) Arrays are (almost) idenqcal to pointers char *string and char string[] are nearly idenqcal declaraqons Differ in subtle ways: incremenqng, declaraqon of filled arrays End of C string marking by 0 in last character Key Concept: Array variable is a pointer to the first (0 th ) element 9/10/13 Fall 2011 - - Lecture #4 17 C Strings String in C is just an array of characters char string[] = "abc"; How do you tell how long a string is? Last character is followed by a 0 byte (aka null terminator ) int strlen(char s[]) { int n = 0; while (s[n]!= 0) n++; return n; 9/10/13 Fall 2013 - - Lecture #4 18 9

Arrays (3/5) Consequences: ar is an array variable, but looks like a pointer ar[0] is the same as *ar ar[2] is the same as *(ar+2) We can use pointer arithmeqc to conveniently access arrays Declared arrays are only allocated while the scope is valid char *foo() { char string[32];...; return string; is incorrect and very very bad 9/10/13 Fall 2011 - - Lecture #4 19 Arrays (4/5) Array size n; want to access from 0 to n- 1, so you should use counter AND uqlize a variable for declaraqon & incrementaqon Bad pabern int i, ar[10]; for(i = 0; i < 10; i++){... BeBer pabern int ARRAY_SIZE = 10 int i, a[array_size]; for(i = 0; i < ARRAY_SIZE; i++){... SINGLE SOURCE OF TRUTH You re uqlizing indirecqon and avoiding maintaining two copies of the number 10 DRY: Don t Repeat Yourself 9/10/13 Fall 2011 - - Lecture #4 20 10

Arrays (5/5) Piwall: An array in C does not know its own length, and its bounds are not checked! Consequence: We can accidentally access off the end of an array Consequence: We must pass the array and its size to any procedure that is going to manipulate it SegmentaQon faults and bus errors: These are VERY difficult to find; be careful! (You ll learn how to debug these in lab) 9/10/13 Fall 2011 - - Lecture #4 21 Array And in Conclusion... Array indexing is syntacqc sugar for pointers a[i] is treated as *(a+i) E.g., three equivalent ways to zero an array: for (i=0; i < size; i++) a[i] = 0; for (i=0; i < size; i++) *(a+i) = 0; for (p=a; p < a+size; p++) *p = 0; 9/10/13 Fall 2011 - - Lecture #4 22 11

What is TRUE about this funcqon? void foo(char *s, char *t) { while (*s) s++; It has syntax errors while (*s++ = *t++) ; No syntax errors; it changes characters in string t to next character in the string s No syntax errors; it copies a string at address t to the string at address s! 23 What is TRUE about this funcqon? void foo(char *s, char *t) { while (*s) s++; It has syntax errors while (*s++ = *t++) ; No syntax errors; it changes characters in string t to next character in the string s No syntax errors; it copies a string at address t to the string at address s! 24 12

QuesQon: Which statement is FALSE regarding C and Java? Arrays in C are just pointers to the 0- th element As Java was derived from C, it has the same control flow constructs Like Java, in C you can check the length of an array ( a.length gives no. elements in a) 25 QuesQon: Which statement is FALSE regarding C and Java? Arrays in C are just pointers to the 0- th element As Java was derived from C, it has the same control flow constructs Like Java, in C you can check the length of an array ( a.length gives no. elements in a) 26 13

pointer + number Pointer ArithmeQc pointer number E.g., pointer + 1 adds 1 something to a pointer char *p; char a; char b; p = &a; p += 1; Adds 1*sizeof(char) to the memory address In each, p now points to b (Assuming compiler doesn t reorder variables in memory) Pointer arithme)c should be used cau)ously int *p; int a; int b; p = &a; p += 1; Adds 1*sizeof(int) to the memory address 9/10/13 Fall 2013 - - Lecture #4 27 Arrays and Pointers Array pointer to the iniqal (0th) array element a[i] *(a+i) An array is passed to a funcqon as a pointer The array size is lost! Usually bad style to interchange arrays and pointers Avoid pointer arithmeqc! Passing arrays: Really int *array int foo(int array[], unsigned int size) { array[size - 1] Must explicitly pass the size int main(void) { int a[10], b[5]; foo(a, 10) foo(b, 5) 9/10/13 Fall 2013 - - Lecture #4 28 14

Arrays and Pointers int foo(int array[], unsigned int size) { printf( %d\n, sizeof(array)); int main(void) { int a[10], b[5]; foo(a, 10) foo(b, 5) printf( %d\n, sizeof(a)); What does this print?... because array is really a pointer (and a pointer is architecture dependent, but likely to be 8 on modern machines!) What does this print? 8 40 9/10/13 Fall 2013 - - Lecture #4 29 Arrays and Pointers int i; int array[10]; for (i = 0; i < 10; i++) { array[i] = ; int *p; int array[10]; for (p = array; p < &array[10]; p++) { *p = ; These code sequences have the same effect! 9/10/13 Fall 2013 - - Lecture #4 30 15

Arrays Administrivia Pointer arithmeqc Arrays vs. pointers Technology Break Pointer Problems CriQcisms of C And in Conclusion, Agenda 9/10/13 Fall 2013 - - Lecture #4 31 Administrivia CS61c is relentless! Lab #2, HW #2 posted HW #2 due Sunday before midnight Midterm rooms determined! 1 Pimental, 10 Evans, 155 Dwinelle 9/10/13 Fall 2013 - - Lecture #4 32 16

CS 61c in the News 9/10/13 Fall 2013 - - Lecture #4 33 Pointers and Arrays Administrivia Pointer arithmeqc Arrays vs. pointers Technology Break Pointer Problems CriQcisms of C And in Conclusion... Agenda 9/10/13 Fall 2013 - - Lecture #4 34 17

Pointer ArithmeQc (1/2) Since a pointer is just a memory address, we can add to it to step through an array p+1 correctly computes a ptr to the next array element automaqcally depending on sizeof(type) *p++ vs. (*p)++? x = *p++ x = *p; p = p + 1; x = (*p)++ x = *p; *p = *p + 1; This is a C syntax/seman)cs thing What if we have an array of large structs (objects)? C takes care of it in the same way it handles arrays 9/10/13 Fall 2013 - - Lecture #4 35 Every addiqon or subtracqon to a pointer steps the number of bytes of thing it is declared to point to This is why type- casqng can get you into trouble 1 byte for a char, 4 bytes for an int, etc. Following are equivalent: int get(int array[], int n) { return (array[n]); // OR... return *(array + n); Pointer ArithmeQc (2/2) 9/10/13 Fall 2013 - - Lecture #4 36 18

If the first prinw outputs 100 5 5 10, what will the next two prinw output? 101 10 5 10 101 11 5 11 104 10 5 10 104 11 5 11 101 <other> 5 10 101 <3- others>! int main(void){ int A[] = {5,10; int *p = A; 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]); 5 10 A[0] A[1] p 37 If the first prinw outputs 100 5 5 10, what will the next two prinw output? 101 10 5 10 101 11 5 11 104 10 5 10 104 11 5 11 101 <other> 5 10 101 <3- others>! int main(void){ int A[] = {5,10; int *p = A; 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]); 5 10 A[0] A[1] p 38 19

Pointers & AllocaQon (1/2) Aker declaring a pointer: int *ptr; ptr doesn t actually point to anything yet (points somewhere, but don t know where). We can either: Make it point to something that already exists, or Allocate room in memory for something new that it will point to 9/10/13 Fall 2013 - - Lecture #4 39 Pointers & AllocaQon (2/2) PoinQng to something that already exists: int *ptr, var1, var2; var1 = 5; ptr = &var1; var2 = *ptr; var1 and var2 have space implicitly allocated for them ptr? var1? 5 var2? 5 9/10/13 Fall 2013 - - Lecture #4 40 20

Arrays (one element past array must be valid) Array size n; want to access from 0 to n- 1, but test for exit by comparing to address one element past the array int ar[10], *p, *q, sum = 0;... p = &ar[0]; q = &ar[10]; while (p!= q) /* sum = sum + *p; p = p + 1; */ sum += *p++; Is this legal? C defines that one element past end of array must be a valid address, i.e., will not cause an bus error or address error 9/10/13 Fall 2013 - - Lecture #4 41 Pointer ArithmeQc What is valid pointer arithmeqc? Add an integer to a pointer Subtract 2 pointers (in the same array) Compare pointers (<, <=, ==,!=, >, >=) Compare pointer to NULL (indicates that the pointer points to nothing) Everything else is illegal since it makes no sense: Adding two pointers MulQplying pointers Subtract pointer from integer 9/10/13 Fall 2013 - - Lecture #4 42 21

Pointer ArithmeQc to Copy Memory We can use pointer arithmeqc to walk through memory: void copy(int *from, int *to, int n) { int i; for (i=0; i<n; i++) { *to++ = *from++; Note we had to pass size (n) to copy 9/10/13 Fall 2013 - - Lecture #4 43 Arrays vs. Pointers Array name is a read- only pointer to the 0th element of the array 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 wriben: while (s[n]) int strlen(char *s) { int n = 0; while (s[n]!= 0) n++; return n; 9/10/13 Fall 2013 - - Lecture #4 44 22

Pointer ArithmeQc And in Conclusion... 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! 9/10/13 Fall 2013 - - Lecture #4 45 Which one of the pointer arithmeqc operaqons is INVALID? Pointer + pointer Pointer integer Integer + pointer 46 23

Which one of the pointer arithmeqc operaqons is INVALID? Pointer + pointer Pointer integer Integer + pointer 47 Which one of the pointer comparisons is INVALID? Compare pointer to pointer Compare pointer to integer Compare pointer to 0 48 24

Which one of the pointer comparisons is INVALID? Compare pointer to pointer Compare pointer to integer Compare pointer to 0 49 Pointers and FuncQons (1/2) What if the thing you want changed is a pointer? What gets printed? void IncrementPtr(int *p) { p = p + 1; A q *q = 50 int A[3] = {50, 60, 70; int *q = A; IncrementPtr(q); printf( *q = %d\n, *q); 50 60 70 9/10/13 Fall 2013 - - Lecture #4 50 25

Pointers and FuncQons (2/2) SoluQon! Pass a pointer to a pointer, declared as **h Now what gets printed? void IncrementPtr(int **h) { *h = *h + 1; A q *q = 60 q int A[3] = {50, 60, 70; int *q = A; IncrementPtr(&q); printf( *q = %d\n, *q); 50 60 70 9/10/13 Fall 2013 - - Lecture #4 51 C String Standard FuncQons #include <string.h> int strlen(char *string); Compute the length of string int strcmp(char *str1, char *str2); Return 0 if str1 and str2 are idenqcal (how is this different from str1 == str2?) char *strcpy(char *dst, char *src); Copy contents of string src to the memory at dst. Caller must ensure that dst has enough memory to hold the data to be copied Note: dst = src only copies pointers, not string itself 9/10/13 Fall 2013 - - Lecture #4 52 26

Pointers and Arrays Pointer arithmeqc Administrivia Arrays vs. pointers Technology Break Pointer Problems CriQcisms of C And in Conclusion, Agenda 9/10/13 Fall 2013 - - Lecture #4 53 Arrays Pointer arithmeqc Administrivia Arrays vs. pointers Technology Break Pointer Problems CriQcisms of C And in Conclusion, Agenda 9/10/13 Fall 2013 - - Lecture #4 54 27

SegmentaQon Fault vs. Bus Error http://www.hyperdictionary.com/ Bus Error A fatal failure in the execuqon of a machine language instrucqon resulqng from the processor detecqng an anomalous condiqon on its bus. Such condiqons include invalid address alignment (accessing a mulq- byte number at an odd address), accessing a physical address that does not correspond to any device, or some other device- specific hardware error. A bus error triggers a processor- level excepqon which Unix translates into a SIGBUS signal which, if not caught, will terminate the current process. SegmentaQon Fault An error in which a running Unix program abempts to access memory not allocated to it and terminates with a segmentaqon violaqon error and usually a core dump. 9/10/13 Fall 2013 - - Lecture #4 55 C String Problems Common mistake is to forget to allocate an extra byte for the null terminator More generally, C requires the programmer to manage memory manually (unlike Java or C++) When creaqng a long string by concatenaqng several smaller strings, the programmer must insure there is enough space to store the full string! What if you don t know ahead of Qme how big your string will be? Buffer overrun security holes! 9/10/13 Fall 2013 - - Lecture #4 56 28

CriQcisms of C - Syntax K&R: C, like any other language, has its blemishes. Some of the operators have the wrong precedence; some parts of the syntax could be beter. Precedence: == binds more Qghtly than &,! x & 1 == 0 means x & (1 == 0)!!!!!!!vs. (x & 1) == 0! 15 levels of precedence for 45 operators K&R p. 53 Therefore use () 9/10/13 Fall 2013 - - Lecture #4 57 CriQcisms of C - Syntax Difference between assignment and equality a = b is assignment a == b is an equality test One of the most common errors for beginning C programmers! One pabern (when comparing with constant) is to put the var on the right! If you happen to use =, it won t compile! if (3 == a) {... 9/10/13 Fall 2013 - - Lecture #4 58 29

CriQcisms of C - Syntax Syntax: confusion about = and ==! if (a=b) is true if a 0 aker assignment Syntax: *p++ means get value at address pointed to by p, then increment p to point to next data item *--p means decrement p to point to the previous data item and that value 9/10/13 Fall 2013 - - Lecture #4 59 CriQcisms of C - Syntax Case statement (switch) requires proper placement of break to work properly Will do all cases unql sees a break switch(ch){! case + : /* does + and - */! case - : break;! case * : break;! default:!!!9/10/13 Fall 2013 - - Lecture #4 60 30

CriQcisms of C Type casqng Type casqng - pretend that a variable declared in one type is actually of another type int x, y, *p;! y = *p; /* legal */! y = *x; /* illegal */! y = *((int *)x); /* legal! */!!! 9/10/13 Fall 2013 - - Lecture #4 61 CriQcisms of C - FuncQonality No runqme checking of array bounds!! 9/10/13 Fall 2013 - - Lecture #4 62 31

And in Conclusion, Pointers are aliases to variables Pointers can be used to index into arrays Strings are (null terminated) arrays of characters Pointers are the source of many bugs in C, so handle with care C, like all languages, has flaws but its small and useful language for some tasks 9/10/13 Fall 2013 - - Lecture #4 63 32