Topic 4: C Data Structures CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering.

Slides:



Advertisements
Similar presentations
CS61CL L01 Introduction (1) Huddleston, Summer 2009 © UCB Introduction to C Jeremy Huddleston inst.eecs.berkeley.edu/~cs61c.
Advertisements

An introduction to pointers in c
Programming and Data Structure
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Kernighan/Ritchie: Kelley/Pohl:
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.
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 L03 Introduction to C (pt 2) (1) Garcia, Fall 2006 © UCB Lecturer SOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C.
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 L4 C Memory Management (1) Beamer, Summer 2007 © UCB Scott Beamer, Instructor inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #4.
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) Garcia, Fall 2005 © UCB Lecturer PSOE, new dad Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C : Machine.
Pointers Pointer - A pointer is a derived data type; that is it is a data type built from one of the standard types. Its value is any of the addresses.
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.
Declaring Arrays Declare an array of 10 elements: int nums[10]; Best practice: #define SIZE 10 int nums[SIZE]; // cannot be int[SIZE] nums; C99: int nums[someVariable]
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.
CS 61C L04 C Pointers (1) Garcia, Spring 2004 © UCB Lecturer PSOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C : Machine.
Pointers Applications
CS 61C L03 C Arrays (1) A Carle, Summer 2006 © UCB inst.eecs.berkeley.edu/~cs61c/ CS61C : Machine Structures Lecture #3: C Pointers & Arrays
C Arrays. One-Dimensional Arrays Proper ways of declare an array in C: int hours[ 24]; double Temp [24]; int test_score [15] = { 77, 88, 99, 100, 87,
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
Instructor: Justin Hsia 6/26/2013Summer Lecture #31 CS 61C: Great Ideas in Computer Architecture C Arrays, Strings, More Pointers.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
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
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:
IT 252 Computer Organization and Architecture Introduction to the C Programming Language Richard Helps (developed from slides from C. Teng and textbook.
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.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
CS 61C: Great Ideas in Computer Architecture Introduction to C, Part II Instructors: Krste Asanovic & Vladimir Stojanovic
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
C Primer Session – 1/25/01 Outline Hello World Command Line Arguments Bit-wise Operators Dynamic Memory / Pointers Function Parameters Structures.
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.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Instructor: Justin Hsia 6/20/2012Summer Lecture #31 CS 61C: Great Ideas in Computer Architecture C Arrays, Strings, More Pointers.
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.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
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
IT 252 Computer Organization and Architecture
C Programming Tutorial – Part I
CSE 303 Concepts and Tools for Software Development
March, 2006 Saeid Nooshabadi
Arrays in C.
C help session: Tonight 306 Soda
CS61C - Machine Structures Lecture 4 C Structures Memory Management
There is one handout today at the front and back of the room!
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
March, 2006 Saeid Nooshabadi
Presentation transcript:

Topic 4: C Data Structures CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University of California, San Diego

Arrays  Declaration: int ar[2]; declares a 2-element integer array. int ar[] = {795, 635}; declares and fills a 2-element integer array.  Accessing elements: ar[num]; returns the num th element.

Arrays  Arrays are (almost) identical to pointers  char *string and char string[] are nearly identical declarations  They differ in very subtle ways: incrementing, declaration of filled arrays  Key Concept: An array variable is a pointer to the first element.

Arrays  Consequences:  ar is a pointer  ar[0] is the same as *ar  ar[2] is the same as *(ar+2)  We can use pointer arithmetic to access arrays more conveniently.  Declared arrays are only allocated while the scope is valid char *foo() { char string[32];...; return string;} is incorrect

Arrays  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 a[10], *p, *q, sum = 0;... p = &a[0]; q = &a[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., not cause an bus error or address error

Arrays  Array size n ; want to access from 0 to n-1, so you should use counter AND utilize a constant for declaration & incr  Wrong int i, a[10]; for(i = 0; i < 10; i++){... }  Right #define ARRAY_SIZE 10 int i, a[ARRAY_SIZE]; for(i = 0; i < ARRAY_SIZE; i++){... }  Why? SINGLE SOURCE OF TRUTH  You’re utilizing indirection and avoiding maintaining two copies of the number 10

Arrays  Pitfall: An array in C does not know its own length, & bounds not checked!  Consequence: We can accidentally access off the end of an array.  Consequence: We must pass the array and its size to a procedure which is going to traverse it.  Segmentation faults and bus errors:  These are VERY difficult to find, so be careful.

Pointer Arithmetic  Since a pointer is just a memory address, we can add to it to traverse an array.  ptr+1 will return a pointer to the next array element.  *ptr+1 vs. *ptr++ vs. *(ptr+1) ?  What if we have an array of large structs (objects)?  C takes care of it: In reality, ptr+1 doesn’t add 1 to the memory address, but rather adds the size of the 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!¯

int get(int array[], int n) { return (array[n]); // OR... return *(array + n); } Pointer Arithmetic  C knows the size of the thing a pointer points to – every addition or subtraction moves that many bytes.  1 byte for a char, 4 bytes for an int, etc.  So the following are equivalent:

Pointer Arithmetic Question #invalid (1)0 How many of the following are invalid? I.pointer + integer (ptr+1) II.integer + pointer (1+ptr) III.pointer + pointer (ptr + ptr) IV.pointer – integer (ptr – 1_ V.integer – pointer (1 – ptr) VI.pointer – pointer (ptr – ptr) VII.compare pointer to pointer (ptr == ptr) VIII.compare pointer to integer (1 == ptr) IX.compare pointer to 0 (ptr == NULL) X.compare pointer to NULL (ptr == NULL)

How many of the following are invalid? I.pointer + integer (ptr+1) II.integer + pointer (1+ptr) III.pointer + pointer (ptr + ptr) IV.pointer – integer (ptr – 1_ V.integer – pointer (1 – ptr) VI.pointer – pointer (ptr – ptr) VII.compare pointer to pointer (ptr == ptr) VIII.compare pointer to integer (1 == ptr) IX.compare pointer to 0 (ptr == NULL) X.compare pointer to NULL (ptr == NULL) Pointer Arithmetic Instruction Answer #invalid (1)0

Pointers to Pointers  But what if what you want changed is a pointer?  What gets printed? void IncrementPtr(int *p) { p = p + 1; } int A[3] = {50, 60, 70}; int *q = A; IncrementPtr(q); printf(“*q = %d\n”, *q); A q

Pointers to Pointers  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 = A q q

Pointers in C  Why use pointers?  If we want to pass a huge struct or array, it’s easier to pass a pointer than the whole thing.  In general, pointers allow cleaner, more compact code.  So what are the drawbacks?  Pointers are probably the single largest source of bugs in software, so be careful anytime you deal with them.  Dangling reference (premature free)  Memory leaks (tardy free)

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]); } If the first printf outputs , what will the other two printf output? 1: then : then : then 101 4: then 104 5: One of the two printfs causes an ERROR 6: I surrender! Array Question A[1] 510 A[0]p

C Strings  A 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 (null terminator) int strlen(char s[]) { int n = 0; while (s[n] != 0) n++; return n; }

C Strings Headaches  One 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 creating a long string by concatenating several smaller strings, the programmer must insure there is enough space to store the full string!  What if you don’t know ahead of time how big your string will be?

Copying strings  Why not say void copy (char sTo[ ], char sFrom[ ]) { sTo = sFrom; }  We need to make sure that space has been allocated for the destination string  Similarly, you probably don’t want to compare two strings using ==

C String Standard Functions  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 ?)  int 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.  Defined in the header file string.h

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(point p) { printf(“(%d,%d)”, p.x, p.y); }

C structures: Pointers to them  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);

How big are structs?  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

Linked List Example  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 Node *List; /* Create a new (empty) list */ List ListNew(void) { return NULL; }

Linked List Example /* add a string to an existing list */ List list_add(List list, char *string) { struct Node *node = (struct Node*) malloc(sizeof(struct Node)); node->value = (char*) malloc(strlen(string) + 1); strcpy(node->value, string); node->next = list; return node; } node: list: string: “abc” …… NULL ?

Linked List Example /* add a string to an existing list */ List list_add(List list, char *string) { struct Node *node = (struct Node*) malloc(sizeof(struct Node)); node->value = (char*) malloc(strlen(string) + 1); strcpy(node->value, string); node->next = list; return node; } node: list: string: “abc” …… NULL ? ?

Linked List Example /* add a string to an existing list */ List list_add(List list, char *string) { struct Node *node = (struct Node*) malloc(sizeof(struct Node)); node->value = (char*) malloc(strlen(string) + 1); strcpy(node->value, string); node->next = list; return node; } node: list: string: “abc” …… NULL ? “????”

Linked List Example /* add a string to an existing list */ List list_add(List list, char *string) { struct Node *node = (struct Node*) malloc(sizeof(struct Node)); node->value = (char*) malloc(strlen(string) + 1); strcpy(node->value, string); node->next = list; return node; } node: list: string: “abc” …… NULL ? “abc”

Linked List Example /* add a string to an existing list */ List list_add(List list, char *string) { struct Node *node = (struct Node*) malloc(sizeof(struct Node)); node->value = (char*) malloc(strlen(string) + 1); strcpy(node->value, string); node->next = list; return node; } node: list: string: “abc” …… NULL “abc”

Linked List Example /* add a string to an existing list */ List list_add(List list, char *string) { struct Node *node = (struct Node*) malloc(sizeof(struct Node)); node->value = (char*) malloc(strlen(string) + 1); strcpy(node->value, string); node->next = list; return node; } node: …… NULL “abc”

Conclusion  Pointers and arrays are virtually same  C knows how to increment pointers  C is an efficient language, with little protection  Array bounds not checked  Variables not automatically initialized  (Beware) The cost of efficiency is more overhead for the programmer.  “C gives you a lot of extra rope but be careful not to hang yourself with it!”