Instructor: Justin Hsia 6/26/2013Summer 2013 -- Lecture #31 CS 61C: Great Ideas in Computer Architecture C Arrays, Strings, More Pointers.

Slides:



Advertisements
Similar presentations
1 CS 201 Pointers (2) Debzani Deb. 2 Overview Pointers Functions: pass by reference Quiz 2 : Review Q & A.
Advertisements

Kernighan/Ritchie: Kelley/Pohl:
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
CS61C L04 Introduction to C (pt 2) (1) Garcia, Fall 2011 © UCB Reference slides You ARE responsible for the material on these slides (they’re just taken.
CS61C L05 C Structures, Memory Management (1) Garcia, Spring 2005 © UCB Lecturer PSOE Dan Garcia inst.eecs.berkeley.edu/~cs61c.
CS 61C L04 C Pointers (1) Garcia, Fall 2004 © UCB Lecturer PSOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C : Machine.
CS61C L04 Introduction to C (pt 2) (1) Garcia, Spring 2007 © UCB Lecturer SOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C.
CS61C L3 C Pointers (1) Beamer, Summer 2007 © UCB Scott Beamer, Instructor inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #3 – C Strings,
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
CS61C L04 Introduction to C (pt 2) (1) Garcia, Fall 2011 © UCB Lecturer SOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C.
CS 61C L4 Structs (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #4: Strings & Structs
CS61C L04 Introduction to C (pt 2) (1) Garcia, Spring 2008 © UCB Lecturer SOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C.
CS 61C L03 C Arrays (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #3: C Pointers & Arrays
CS 61C L03 C Pointers (1)Garcia / Patterson Fall 2002 © UCB CS61C - Machine Structures Lecture 3 C pointers  Dan Garcia (
CS61C L3 C Pointers (1) Chae, Summer 2008 © UCB Albert Chae Instructor inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #3 – More C intro,
CS61CL L01 Introduction (1) Huddleston, Summer 2009 © UCB Jeremy Huddleston inst.eecs.berkeley.edu/~cs61c CS61CL : Machine Structures Lecture #2 - C Pointers.
Adapted from Dr. Craig Chase, The University of Texas at Austin.
CS 61C L04 C Pointers (1) Garcia, Spring 2004 © UCB Lecturer PSOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C : Machine.
CS 61C L03 C Arrays (1) A Carle, Summer 2006 © UCB inst.eecs.berkeley.edu/~cs61c/ CS61C : Machine Structures Lecture #3: C Pointers & Arrays
CS 61C L04 C Structures, Memory Management (1) Garcia, Fall 2004 © UCB Lecturer PSOE Dan Garcia inst.eecs.berkeley.edu/~cs61c.
CS61C L4 C Pointers (1) Chae, Summer 2008 © UCB Albert Chae Instructor inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #4 –C Strings,
CS 61C Great Ideas in Computer Architecture Lecture 3: Introduction to C, Part II Instructor: Sagar Karandikar
Arrays and Pointers in C Alan L. Cox
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
Chapter 17 Pointers and Arrays. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Pointers and Arrays.
CSC 2400 Computer Systems I Lecture 5 Pointers and Arrays.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
1 Pointers and Arrays. 2 When an array is declared,  The compiler allocates sufficient amount of storage to contain all the elements of the array in.
CS 61C: Great Ideas in Computer Architecture Introduction to C, Part II Instructors: John Wawrzynek & Vladimir Stojanovic
C Programming Day 4. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 More on Pointers Constant Pointers Two ways to.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
November 18, 2015Memory and Pointers in Assembly1 What does this C code do? int foo(char *s) { int L = 0; while (*s++) { ++L; } return L; }
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
Pointers *, &, array similarities, functions, sizeof.
© Oxford University Press All rights reserved. CHAPTER 7 POINTERS.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
Topic 4: C Data Structures CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
Week 7 Part I Kyle Dewey. Overview Code from last time Array initialization Pointers vs. arrays Structs typedef Bubble sort (if time)
CS 61C: Great Ideas in Computer Architecture Introduction to C, Part II Instructors: Krste Asanovic & Vladimir Stojanovic
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
Instructor: Justin Hsia 6/20/2012Summer Lecture #31 CS 61C: Great Ideas in Computer Architecture C Arrays, Strings, More Pointers.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
CS 61C: Great Ideas in Computer Architecture C Pointers Instructors: Vladimir Stojanovic & Nicholas Weaver 1.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
CS61C L04 Introduction to C (pt 2) (1) Garcia, Spring 2010 © UCB Lecturer SOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C.
Computer Organization and Design Pointers, Arrays and Strings in C
Arrays in C.
CS 61C: Great Ideas in Computer Architecture Lecture 3: Pointers
C help session: Tonight 306 Soda
CS61C - Machine Structures Lecture 4 C Structures Memory Management
Lecture 18 Arrays and Pointer Arithmetic
Pointers.
Outline Defining and using Pointers Operations on pointers
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
Chapter 16 Pointers and Arrays
C++ Pointers and Strings
Data Structures and Algorithms Introduction to Pointers
C++ Pointers and Strings
Presentation transcript:

Instructor: Justin Hsia 6/26/2013Summer Lecture #31 CS 61C: Great Ideas in Computer Architecture C Arrays, Strings, More Pointers

Review of Last Lecture C Basics – Variables, Functions, Flow Control, Types, and Structs – Only 0 and NULL evaluate to FALSE Pointers hold addresses – Address vs. Value – Allow for efficient code, but prone to errors C functions “pass by value” – Passing pointers circumvents this 6/26/2013Summer Lecture #32

Struct Clarification Structure definition: – Does NOT declare a variable – Variable type is “struct name” Joint struct definition and typedef – Don’t need to name struct in this case 6/26/2013Summer Lecture #33 struct name { /* fields */ }; typedef struct { /* fields */ } name; name n1; struct name name1, *pn, name_ar[3]; struct nm { /* fields */ }; typedef struct nm name; name n1;

#include int main() { int *p; *p = 5; printf(“%d\n”,*p); } 4 Question: What is the result from executing the following code? Prints 5 (A) Prints garbage (B) Always crashes (C) (D)

Great Idea #1: Levels of Representation/Interpretation 6/26/2013Summer Lecture #35 lw $t0, 0($2) lw $t1, 4($2) sw $t1, 0($2) sw $t0, 4($2) Higher-Level Language Program (e.g. C) Assembly Language Program (e.g. MIPS) Machine Language Program (MIPS) Hardware Architecture Description (e.g. block diagrams) Compiler Assembler Machine Interpretation temp = v[k]; v[k] = v[k+1]; v[k+1] = temp; Logic Circuit Description (Circuit Schematic Diagrams) Architecture Implementation We are here_

Agenda Miscellaneous C Syntax Arrays Administrivia Strings More Pointers – Pointer Arithmetic – Pointer Misc 6/26/2013Summer Lecture #36

Assignment and Equality One of the most common errors for beginning C programmers a = b is assignment a == b is equality test When comparing with a constant, can avoid this by putting the variable on the right! – if (3 == a) {... } Correct – if (3 = a) {... } Won’t compile Comparisons use assigned value – if (a=b) is true if a≠0 after assignment ( b≠0 ) 6/26/2013Summer Lecture #37

Operator Precedence 6/26/2013Summer Lecture #38

Operator Precedence Use parentheses to manipulate Equality test ( == ) binds more tightly than logic ( &, |, &&, || ) – x&1==0 means x&(1==0) instead of (x&1)==0 Pre-increment (++p) takes effect immediately Post-increment (p++) takes effect last 6/26/2013Summer Lecture #39 For precedence/order of execution, see Table 2-1 on p. 53 of K&R

Increment and Dereference Dereference operator ( * ) and in/decrement operators are same level of precedence and are applied from right to left *p++ returns *p, then increments p ++ binds to p before *, but takes effect last *--p decrements p, returns val at that addr -- binds to p before * and takes effect first ++*p increments *p and returns that val * binds first (get val), then increment immediately (*p)-- returns *p, then decrements in mem Post-decrement happens last 6/26/2013Summer Lecture #310

11 Question: What is the output of the following code? char blocks[] = {‘6’,‘1’,‘C’}; char *ptr = blocks, temp; temp = *++ptr; printf(“1: %c\n”, temp); temp = *ptr++; printf(“2: %c\n”, temp); 7878 (A) 7171 (B) 1 (C) (D) 1212

Agenda Miscellaneous C Syntax Arrays Administrivia Strings More Pointers – Pointer Arithmetic – Pointer Misc 6/26/2013Summer Lecture #312

Array Basics Declaration: int ar[2]; declares a 2-element integer array (just a block of memory) int ar[] = {795, 635}; declares and initializes a 2-element integer array Accessing elements: ar[num] returns the num th element – Zero-indexed 6/26/2013Summer Lecture #313

Arrays Basics Pitfall: An array in C does not know its own length, and its bounds are not checked! – We can accidentally access off the end of an array – We must pass the array and its size to any procedure that is going to manipulate it Mistakes with array bounds cause segmentation faults and bus errors – Be careful! These are VERY difficult to find (You’ll learn how to debug these in lab) 6/26/2013Summer Lecture #314

Accessing an Array Array size n: access entries 0 to n-1 Use separate variable for declaration & bound – Bad pattern int i, ar[10]; for(i=0; i<10; i++) {...} – Better pattern int ARRAY_SIZE = 10; int i, ar[ARRAY_SIZE]; for(i=0; i<ARRAY_SIZE; i++) {...} 6/26/2013Summer Lecture #315 Single source of truth! Bad Pattern Better Pattern

Arrays and Pointers Arrays are (almost) identical to pointers – char *string and char string[] are nearly identical declarations – Differ in subtle ways: initialization, sizeof(), etc. Key Concept: An array variable looks like a pointer to the first (0 th ) element – ar[0] same as *ar ; ar[2] same as *(ar+2) – We can use pointer arithmetic to conveniently access arrays An array variable is read-only (no assignment) (i.e. cannot use “ ar = ”) 6/26/2013Summer Lecture #316

Array and Pointer Example ar[i] is treated as *(ar+i) To zero an array, the following three ways are equivalent: 1)for(i=0; i<SIZE; i++) ar[i] = 0; 2)for(i=0; i<SIZE; i++) *(ar+i) = 0; 3)for(p=ar; p<ar+SIZE; p++) *p = 0; These use pointer arithmetic, which we will get to shortly 6/26/2013Summer Lecture #317

void foo() { int *p, a[4], x; p = &x; *p = 1; // or p[0] printf("*p:%u, p:%u, &p:%u\n",*p,p,&p); *a = 2; // or a[0] printf("*a:%u, a:%u, &a:%u\n",*a,a,&a); } Arrays Stored Differently Than Pointers 6/26/2013Summer Lecture #318 ?... ??4021 *p:1, p:40, &p:20 *a:2, a:24, &a:24 K&R: “An array__. name is not a variable”. a 24 ? … px

Arrays and Functions Declared arrays only allocated while the scope is valid: char *foo() { char string[32];...; return string; } An array is passed to a function as a pointer: int foo(int ar[], unsigned int size) {... ar[size-1]... } 6/26/2013Summer Lecture #319 BAD Must explicitly pass the size! Really int *ar

Arrays and Functions Array size gets lost when passed to a function What prints in the following code: int foo(int array[], unsigned int size) {... printf(“%d\n”, sizeof(array)); } int main(void) { int a[10], b[5];... foo(a, 10)... printf(“%d\n”, sizeof(a)); } 6/26/2013Summer Lecture #320 ??? sizeof(int *) 10*sizeof(int)

Agenda Miscellaneous C Syntax Arrays Administrivia Strings More Pointers – Pointer Arithmetic – Pointer Misc 6/26/2013Summer Lecture #321

Administrivia Lab 2 tomorrow HW1 due Sunday night Lab 3 (big lab) next Tue (July 2) HW2 released Fri, due next Wed (July 3) Suggested plan of attack: – Finish HW1 by Sat night – Do 1 st half of Lab 3 Sun, start HW2 – Do 2 nd half of Lab 3 Tue, finish HW2 by Wed 6/26/2013Summer Lecture #322

Agenda Miscellaneous C Syntax Arrays Administrivia Strings More Pointers – Pointer Arithmetic – Pointer Misc 6/26/2013Summer Lecture #323

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 ( ‘\0’ ) (a.k.a. “null terminator”) 6/26/2013Summer Lecture #324 int strlen(char s[]) { int n = 0; while (s[n] != 0) n++; return n; } Array size here is 4 This means you need an extra space in your array!!!

C String Standard Functions Accessible with #include int strlen(char *string); – Returns the length of string (not including null term) 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 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 pointer (the address) 6/26/2013Summer Lecture #325

String Examples #include int main () { char s1[10], s2[10], s3[]=“hello”, *s4=“hola”; strcpy(s1,“hi”); strcpy(s2,“hi”); } Value of the following expressions? 6/26/2013Summer Lecture #326 sizeof(s1) 10 strlen(s1) 2 s1==s2 0 strcmp(s1,s2) 0 strcmp(s1,s3) 4 strcmp(s1,s4) -6 (s1 > s3) (s1 < s4) Point to different locations!

Always throws an error (A) Changes characters in string t to the next character in the string s (B) Copies a string at address t to the string at address s (C)(D) 27 Question: What does this function do when called? void foo(char *s, char *t) { while (*s) s++; while (*s++ = *t++) ; }

Agenda Miscellaneous C Syntax Arrays Administrivia Strings More Pointers – Pointer Arithmetic – Pointer Misc 6/26/2013Summer Lecture #328

Pointer Arithmetic pointer ± number – e.g. pointer + 1 adds 1 something to the address Compare what happens: (assume a at address 100) Pointer arithmetic should be used cautiously 6/26/2013Summer Lecture #329 Adds 1*sizeof(char) Adds 1*sizeof(int) char *p; char a;int *p; int a; p = &a; printf(“%u %u\n”,p,p+1);

Pointer Arithmetic A pointer is just a memory address, so we can add to/subtract from it to move through an array p+1 correctly increments p by sizeof(*p) – i.e. moves pointer to the next array element What about an array of large structs (objects)? – Struct declaration tells C the size to use, so handled like basic types 6/26/2013Summer Lecture #330

Pointer Arithmetic What is valid pointer arithmetic? – 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 – Multiplying pointers – Subtract pointer from integer 6/26/2013Summer Lecture #331

Pointer Arithmetic to Copy Memory We can use pointer arithmetic to “walk” through memory: 6/26/2013Summer Lecture #332 void copy(int *from, int *to, int n) { int i; for (i=0; i<n; i++) { *to++ = *from++; } We have to pass the size ( n ) to copy

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]); } 33 Question: The first printf outputs What will the next two printf output? then (A) then (B) then (C) (D) A[1] 510 A[0] p

Get To Know Your Staff Category: Cal 6/26/2013Summer Lecture #334

Agenda Miscellaneous C Syntax Arrays Administrivia Strings More Pointers – Pointer Arithmetic – Pointer Misc 6/26/2013Summer Lecture #335

Pointers and Allocation When you declare a pointer (e.g. int *ptr; ), it doesn’t actually point to anything yet – It points somewhere (garbage; don’t know where) – Dereferencing will usually cause an error Option 1: Point to something that already exists – int *ptr,var; var = 5; ptr = &var1; – var has space implicitly allocated for it (declaration) Option 2: Allocate room in memory for new thing to point to (next lecture) 6/26/2013Summer Lecture #336

Pointers and Arrays Want to access all of array of size n and 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++; Yes! 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 6/26/2013Summer Lecture #337 Is this legal?

Pointers and Structures Variable declarations: struct Point { int x; int y; struct Point *p; }; struct Point pt1; struct Point pt2; struct Point *ptaddr; Valid operations: /* dot notation */ int h = pt1.x; pt2.y = pt1.y; /* arrow notation */ int h = ptaddr->x; int h = (*ptaddr).x; /* This works too */ pt1 = pt2; 6/26/2013Summer Lecture #338 Cannot contain an instance of itself, but can point to one Copies contents

Pointers to Pointers Pointer to a pointer, declared as **h Example: 6/26/2013Summer Lecture #339 void IncrementPtr(int **h) { *h = *h + 1; } int A[3] = {50, 60, 70}; int *q = A; IncrementPtr(&q); printf(“*q = %d\n”, *q); *q = A q q

40 Question: Struct and Pointer Practice Assuming everything is properly initialized, what do the following expressions evaluate to? struct node { char *name; struct node *next; }; struct node *ar[5]; struct node **p = ar;... /* fill ar with initialized structs */ address ☐ data ☐ invalid ☐ 1)&p 2)p->name 3)p[7]->next 4)*(*(p + 2)) 5)*(p[0]->next) 6)(*p)->next->name

41 Answers: Struct and Pointer Practice 1)&p address (ptr to ptr to ptr) “address of” operator returns an address 2)p->name invalid Attempt to access field of a pointer 3)p[7]->next invalid Increment p into unknown memory, then dereference 4)*(*(p + 2)) data (struct node) Move along array, access pointer, then access struct 5)*(p[0]->next) data (struct node) This is tricky. p[0] = *(p + 0) is valid and accesses the array of pointers, where -> operator correctly accesses field of struct, and dereference leaves us at another struct. 6)(*p)->next->name address (char array) next field points to struct, access name field, which is, itself, a pointer (string)

Summary Pointers and array variables are very similar – Can use pointer or array syntax to index into arrays Strings are null-terminated arrays of characters Pointer arithmetic moves the pointer by the size of the thing it’s pointing to Pointers are the source of many bugs in C, so handle with care 6/26/2013Summer Lecture #342