Lecture P8: Pointers and Linked Lists

Similar documents
Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering

Analysis of a Search Algorithm

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

recursion, O(n), linked lists 6/14

1. Relational database accesses data in a sequential form. (Figures 7.1, 7.2)

10CS35: Data Structures Using C

CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis. Linda Shapiro Winter 2015

PES Institute of Technology-BSC QUESTION BANK

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

Lecture 10: Dynamic Memory Allocation 1: Into the jaws of malloc()

ADTs,, Arrays, Linked Lists

Sequential Data Structures

The Advantages of Dan Grossman CSE303 Spring 2005, Lecture 25

Stacks. Linear data structures

Lecture 7: Machine-Level Programming I: Basics Mohamed Zahran (aka Z)

Coding Rules. Encoding the type of a function into the name (so-called Hungarian notation) is forbidden - it only confuses the programmer.

Data Structures Using C++ 2E. Chapter 5 Linked Lists

C++ Programming Language

Illustration 1: Diagram of program function and data flow

How To Write Portable Programs In C

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push)

C Dynamic Data Structures. University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell

Lecture 12 Doubly Linked Lists (with Recursion)

Lecture 11 Array of Linked Lists

Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011

Output: struct treenode{ int data; struct treenode *left, *right; } struct treenode *tree_ptr;

DATA STRUCTURES USING C

Data Structure with C

The Plan Today... System Calls and API's Basics of OS design Virtual Machines

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Efficient representation of integer sets

Sources: On the Web: Slides will be available on:

language 1 (source) compiler language 2 (target) Figure 1: Compiling a program

Industrial Programming

Data Structure [Question Bank]

Outline: Operating Systems

DNA Data and Program Representation. Alexandre David

The following themes form the major topics of this chapter: The terms and concepts related to trees (Section 5.2).

Virtual vs Physical Addresses

Binary Heap Algorithms

Physical Data Organization

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Interpreters and virtual machines. Interpreters. Interpreters. Why interpreters? Tree-based interpreters. Text-based interpreters

Programming languages C

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

5. A full binary tree with n leaves contains [A] n nodes. [B] log n 2 nodes. [C] 2n 1 nodes. [D] n 2 nodes.

Code Refactoring and Defects

Abstract Data Type. EECS 281: Data Structures and Algorithms. The Foundation: Data Structures and Abstract Data Types

Linked Lists, Stacks, Queues, Deques. It s time for a chainge!

LINKED DATA STRUCTURES

System Calls and Standard I/O

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct

COS 318: Operating Systems. File Layout and Directories. Topics. File System Components. Steps to Open A File

Numerical Matrix Analysis

Lecture Notes on Binary Search Trees

Lecture 15: Linked Structures

Parameter Passing. Parameter Passing. Parameter Passing Modes in Fortran. Parameter Passing Modes in C

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

Client-server Sockets

Lecture Data Types and Types of a Language

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Chapter 7D The Java Virtual Machine

X86-64 Architecture Guide

Stacks. Data Structures and Data Types. Collections

Fast Arithmetic Coding (FastAC) Implementations

ECE 250 Data Structures and Algorithms MIDTERM EXAMINATION /5:15-6:45 REC-200, EVI-350, RCH-106, HH-139

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

CSE 326, Data Structures. Sample Final Exam. Problem Max Points Score 1 14 (2x7) 2 18 (3x6) Total 92.

Specific Simple Network Management Tools

TREE BASIC TERMINOLOGIES

Two Parts. Filesystem Interface. Filesystem design. Interface the user sees. Implementing the interface

System Software Prof. Dr. H. Mössenböck

The C Programming Language course syllabus associate level

Data Structures and Data Manipulation

Programming Language Features (cont.) CMSC 330: Organization of Programming Languages. Parameter Passing in OCaml. Call-by-Value

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Sample Questions Csci 1112 A. Bellaachia

List, Stack and Queue. Tom Chao Zhou CSC2100B Data Structures Tutorial 3

Parallelization: Binary Tree Traversal

Linked List as an ADT (cont d.)

Lecture Notes on Binary Search Trees

Unit Write iterative and recursive C functions to find the greatest common divisor of two integers. [6]

The programming language C. sws1 1

Lecture Notes on Linear Search

Converting a Number from Decimal to Binary

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Principles of Database Management Systems. Overview. Principles of Data Layout. Topic for today. "Executive Summary": here.

Course: Programming II - Abstract Data Types. The ADT Queue. (Bobby, Joe, Sue, Ellen) Add(Ellen) Delete( ) The ADT Queues Slide Number 1

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

TECHNICAL UNIVERSITY OF CRETE DATA STRUCTURES FILE STRUCTURES

1 Abstract Data Types Information Hiding

7th Marathon of Parallel Programming WSCAD-SSC/SBAC-PAD-2012

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

C Interview Questions

Today. Binary addition Representing negative numbers. Andrew H. Fagg: Embedded Real- Time Systems: Binary Arithmetic

Arithmetic and Algebra of Matrices

Transcription:

Lecture P8: Pointers and Linked Lists J Q 5 NULL Pointer Overview Basic computer memory abstraction. Indexed sequence of bits. Address = index. Pointer = VARIABLE that stores memory address. Uses. Allow function to change inputs. Better understanding of arrays. Create "linked lists." addr value 0 0 1 1 2 1 3 1 4 0 5 1 6 0 7 0 8 1 9 0 10 1 256GB 1 2 Pointers in TOY Pointers in C Unix Variable that stores the value of a single MEMORY ADDRESS. In TOY, memory addresses are 00 FF. indexed addressing: store a memory address in a register Very powerful and useful programming mechanism. Confusing and easy to abuse! Address 9 1 Memory location stores a "pointer" to another memory address of interest. 0 D0CC 7 D0D0 0000 5 D204 3 D208 C pointers. % gcc pointer.c % a.out If x is an integer: x = 7 &x is a pointer to x (memory address of x) px = ffbefb24 If px is a pointer to an integer: *px = 7 *px is the integer pointer.c allocate storage for pointer to int int x; int *px; x = 7; px = &x; printf(" x = %d\n"); printf(" px = %p\n", px); printf("*px = %d\n", *px); 3 5

Pointers as Arguments to Functions Goal: function that swaps values of two integers. Pointers as Arguments to Functions Goal: function that swaps values of two integers. A first attempt: badswap.c Now, one that works. swap.c only swaps copies of x and y void swap(int a, int b) { int t; t = a; a = b; b = t; changes value stored in memory address for x and y void swap(int *pa, int *pb) { int t; t = *pa; *pa = *pb; *pb = t; int x = 7, y = 10; swap(x, y); printf("%d %d\n", x, y); int x = 7, y = 10; swap(&x, &y); printf("%d %d\n", x, y); 6 7 Linked List Overview Linked List Goal: deal with large amounts of data. Organize data so that it is easy to manipulate. Time and space efficient. Basic computer memory abstraction. Indexed sequence of bits. Address = index. Need higher level abstractions to bridge gap. Array. Struct. LINKED LIST Binary tree. Database. addr value 0 0 1 1 2 1 3 1 4 0 5 1 6 0 7 0 8 1 9 0 10 1 256GB 1 Fundamental data structure. HOMOGENEOUS collection of values (all same type). Store values ANYWHERE in memory. Associate LINK with each value. Use link for immediate access to the NEXT value. Possible memory representation of x 9 + 3x 5 + 7. Assume linked list starts in location. Address 1 9 7 D0CC D0D0 0 0000 3 head 1 9 7 0 0000 NULL 3 5 D204 D208 5 8 10

Linked List Fundamental data structure. HOMOGENEOUS collection of values (all same type). Store values ANYWHERE in memory. Associate LINK with each value. Use link for immediate access to the NEXT value. Linked List vs. Array Polynomial example illustrates basic tradeoffs. Sparse polynomial = few terms, large exponent. Ex. x 1000000 + 5x 50000 + 7 Dense polynomial = mostly nonzero coefficients. Ex. x 7 + x 6 + 3x 4 + 2x 3 + 1 Possible memory representation of x 9 + 3x 5 + 7. Assume linked list starts in location. Huge Sparse Polynomial array linked Huge Dense Polynomial array linked Address D0CC D0D0 D204 D208 space huge tiny space huge 3 * huge 1 9 7 0 0000 3 5 time instant tiny time instant huge! Advantage: space proportional to amount of info.! Disadvantage: can only get to next item quickly. Lesson: know space and time costs. Axiom 1: there is never enough space. Axiom 2: there is never enough time. Time to determine coefficient of x k. 11 12 Overview of Linked Lists in C Not directly built in to C language. Need to know: How to associate pieces of information. User-define type using struct. Include struct field for coefficient and exponent. C code to represent of x 9 + 3x 5 + 7. Statically, using nodes. memory address of next node Linked List for Polynomial typedef struct node *link; struct node { int coef; int exp; link next; ; poly1.c define node to store two integers How to specify links. Include struct field for POINTER to next linked list element. How to reserve memory to be used. Allocate memory DYNAMICALLY (as you need it). malloc() How to use links to access information. -> and. operators initialize data link up nodes struct node p, q, r; p.coef = 1; p.exp = 9; q.coef = 3; q.exp = 5; r.coef = 7; r.exp = 0; p.next = &q; q.next = &r; r.next = NULL; 13 14

Linked List for Polynomial Better Programming Style C code to represent of x 9 + 3x 5 + 7. Statically, using nodes. Dynamically using links. initialize data allocate enough memory to store node link up nodes of list Study this code: tip of iceberg! poly2.c #include <stdlib.h> typedef struct node *link; struct node { ; link x, y, z; x = malloc(sizeof *x); x->coef = 1; x->exp = 9; y = malloc(sizeof *y); y->coef = 3; y->exp = 5; z = malloc(sizeof *z); z->coef = 7; z->exp = 0; x->next = y; y->next = z; z->next = NULL; Write separate function to handle memory allocation and initialization. check if malloc fails Initialize pointers to NULL #include <stdlib.h> poly3.c link NEWnode(int c, int e, link n) { link x = malloc(sizeof *x); if (x == NULL) { printf("out of memory.\n"); exit(exit_failure); x->coef = c; x->exp = e; x->next = n; return x; link x = NULL; x = NEWnode(7, 0, x); x = NEWnode(3, 5, x); x = NEWnode(1, 9, x); 15 16 Review of Stack Interface In Lecture P5, we created ADT for stack. We implemented stack using arrays. Now, we give alternate implementation using linked lists. Stack Implementation With Linked Lists stacklist.c #include <stdlib.h> #include "STACK.h" STACK.h void STACKinit(void); int STACKisempty(void); void STACKpush(int); int STACKpop(void); void STACKshow(void); client uses data type, without regard to how it is represented or implemented. client.c #include "STACK.h" int a, b; STACKinit(); STACKpush(a); b = STACKpop(); static to make it a true ADT typedef struct STACKnode* link; struct STACKnode { int item; standard linked link next; list data structure ; static link head = NULL; void STACKinit(void) { head = NULL; int STACKisempty(void) { return head == NULL; head points to top node on stack 17 18

Stack Implementation With Linked Lists Stack Implementation With Linked Lists stacklist.c (cont) allocate memory and initialize new node insert at beginning of list stacklist.c (cont) link NEWnode(int item, link next) { link x = malloc(sizeof *x); if (x == NULL) { printf("out of memory.\n"); exit(exit_failure); x->item = item; x->next = next; return x; void STACKpush(int item) { head = NEWnode(item, head); 19 int STACKpop(void) { int item; if (head == NULL) { printf("stack underflow.\n"); exit(exit_failure); item = head->item; link x = head->next; free(head); head = x; return item; free is opposite of malloc: gives memory back to system traverse linked list void STACKshow(void) { link x; for (x = head; x!= NULL; x = x-next) printf("%d\n", x->item); 20 Implementing Stacks: Arrays vs. Linked Lists We can implement a stack with either array or linked list, and switch implementation without changing interface or client. %gcc client.c stacklist.c OR %gcc client.c stackarray.c Conclusions Whew, lots of material in this lecture! Pointers are useful, but confusing. Study these slides and carefully read relevant material. Which is better? Array! Requires upper bound MAX on stack size.! Uses space proportional to MAX. Linked List! No need to know stack size ahead of time.! Requires extra space to store pointers.! Dynamically memory allocation is slower. 21 22

Pointers and Arrays Lecture P8: Extra Slides #define N 64 int a[n] = {84, 67, 24,., 89, 90; avg.c for (i = 0; i < N; i++) sum += a[i]; printf("%d\n", sum / N); on arizona, int is 32 bits (4 bytes) 4 byte offset "Pointer arithmetic" &a[0] = a+0 = &a[1] = a+1 = &a[2] = a+2 = a[0] = *a = 84 a[1] = *(a+1) = 67 a[2] = *(a+2) = 24 Memory address D0F8 D0FC 84 67 24 89 90 24 Pointers and Arrays Passing Arrays to Functions Just to stress that a[i] really means *(a+i): 2[a] = *(2+a) = 24 This is legal C, but don t ever do this at home!!! integer (on arizona) takes 4 bytes 4 byte offset "Pointer arithmetic" &a[0] = a+0 = &a[1] = a+1 = &a[2] = a+2 = a[0] = *a = 84 a[1] = *(a+1) = 67 a[2] = *(a+2) = 24 Pass array to function. Pointer to array element 0 is passed instead. #define N 64 avg.c int average(int b[], int n) { receive the value from main Memory address 84 67 24 D0F8 89 D0FC 90 int a[n] = {84, 67, 24,., 89, 90; printf("%d\n", average(a, N)); passes &a[0] = to function 25 26

Why Pass Array as Pointer? Advantages.! Efficiency for large arrays don't want to copy entire array.! Easy to pass "array slice" of "sub-array" to functions. Passing Arrays to Functions Many C programmers use int *b instead of int b[] in function prototype. Emphasizes that array decays to pointer when passed to function. avg.c int average(int b[], int n) { res = average(a+5, 10); compute average of a[5] through a[14] average function int average(int b[], int n) { an equivalent function int average(int *b, int n) { 27 28