CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 7 : September 8.

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

CSCE 3110 Data Structures & Algorithm Analysis
CSEB324 Data Structures & Algorithms
Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.
Singly Linked List BTECH, EE KAZIRANGA UNIVERSITY.
CSCI2100B Linked List Jeffrey
C Structures What is a structure? A structure is a collection of related variables. It may contain variables of many different data types---in contrast.
Dynamic memory allocation
Data Structure Lecture-5
Data Structure Lecture-3 Prepared by: Shipra Shukla Assistant Professor Kaziranga University.
Senem Kumova Metin Spring2009 STACKS AND QUEUES Chapter 10 in A Book on C.
Chapter 6 Structures By C. Shing ITEC Dept Radford University.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
Growing Arrays in C By: Victoria Tielebein CS 265- Spring 2011.
Agenda  Review: pointer & array  Relationship between pointer & array  Dynamic memory allocation.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures.
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
CP104 Introduction to Programming Structure II Lecture 32 __ 1 Data Type planet_t and Basic Operations Abstract Data Type (ADT) is a data type combined.
Programming Languages -1 (Introduction to C) structures Instructor: M.Fatih AMASYALI
C Programming : Elementary Data Structures 2009/04/22 Jaemin
Kernighan/Ritchie: Kelley/Pohl:
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
1 Chapter 6 Priority Queues (Heaps) General ideas of priority queues (Insert & DeleteMin) Efficient implementation of priority queue Uses of priority queues.
Pointers Chapters 6+9 in ABC. abp 12 int a = 1, b = 2, *p; & - reference operator (address) * - dereference operator (value) p = &a; // *p is now 1 abp.
Structures and Lists (and maybe stacks) Chapters 9-10.
Chapter 12 C Data Structures Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
1 CS 201 Dynamic Data Structures Debzani Deb. 2 Run time memory layout When a program is loaded into memory, it is organized into four areas of memory.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 12 – Data Structures Outline 12.1Introduction.
CS Data Structures Chapter 4 Lists.
Lecture 25 Self-Referential Structures Linked Lists
Chapter 12 Data Structure Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Review 1 Introduction Representation of Linear Array In Memory Operations on linear Arrays Traverse Insert Delete Example.
 2007 Pearson Education, Inc. All rights reserved C Data Structures.
Introduction to Data Structures Systems Programming.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Chapter 14 Dynamic Data Structures Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
Lecture 13 Static vs Dynamic Memory Allocation
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
Lists, Stacks and Queues in C Yang Zhengwei CSCI2100B Data Structures Tutorial 4.
Programming Languages -1 (Introduction to C) structures
Structures. Heterogeneous Structures Collection of values of possibly different types. Name the collection. Name the components. Example : Student record.
Introduction to Data Structures Systems Programming Concepts.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
Programming Practice 3 - Dynamic Data Structure
CE 221 Data Structures and Algorithms Chapter 3: Lists, Stacks, and Queues - II Text: Read Weiss, §3.6 1Izmir University of Economics.
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
CNG 140 C Programming (Lecture set 12) Spring Chapter 13 Dynamic Data Structures.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 5.
ENEE150 – 0102 ANDREW GOFFIN Dynamic Memory. Dynamic vs Static Allocation Dynamic  On the heap  Amount of memory chosen at runtime  Can change allocated.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
 Memory from the heap  Dynamic memory allocation using the new operator  Build a dynamic linked list  Another way of traversing a linked list 
Sudeshna Sarkar, CSE, IIT Kharagpur1 Structure and list processing Lecture
Stacks This presentation shows – how to implement the stack – how it can be used in real applications.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Linked Lists Outline Introduction Self-Referential Structures.
Structures CSE 2031 Fall March Basics of Structures (6.1) struct point { int x; int y; }; keyword struct introduces a structure declaration.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
CE 221 Data Structures and Algorithms Chapter 3: Lists, Stacks, and Queues - II Text: Read Weiss, §3.6 1Izmir University of Economics.
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
 In general, Queue is line of person waiting for their turn at some service counter like ticket window at cinema hall, at bus stand or at railway station.
STACKS & QUEUES for CLASS XII ( C++).
Chapter 12 – Data Structures
Dynamic Allocation Review Structure and list processing
12 C Data Structures.
Introduction to Data Structures
Linked List Sudeshna Sarkar.
Instructor: Ioannis A. Vetsikas
Review & Lab assignments
CS111 Computer Programming
Presentation transcript:

CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 7 : September 8

2 Memory Assignment The following program demonstrates the “wrong” way to assign to a pointer a memory location for it to point to. The variable a is local to the function function_3 and thus when this function ceases to exist the memory for a will probably be deallocated as well. The correct way is to allocate some memory where the pointer can be assigned to as is demonstrated by the next program… void main() { int *a; a = function_3(); printf( “%d\n”, *a ); } int *function_3() { int b; b = 3; return &b; }

3 Valid Memory Assignment #include int *function_3(); void main() { int *a; a = function_3(); printf( “%d\n”, *a ); free( a ); } int *function_3() { int *b; b = (int *) malloc( sizeof( int )); /* NULL? */ *b = 3; return b; }

4 Memory Allocation Functions All functions are declared in void *malloc(size_t size) allocates size bytes and returns a pointer to the new space if possible; otherwise it returns the null pointer. void *calloc(size_t n, size_t size) is same as malloc(n*size), but the allocated storage is also zeroed (it is slower). void *realloc(void *ptr, size_t size) changes size of previously allocated object to size and returns pointer to new space is possible (or NULL otherwise) void free(void *ptr) deallocates previously allocated storage

5 Some suggestions and comments The NULL pointer is a pointer that points to nothing. So if p=NULL; then the statement *p is going to produce a run-time error. void * is a generic pointer type that is returned by all memory functions. By generic one means that void * covers all possible pointers that exist and thus by declaring a pointer as generic (void *) you suggest that it can accommodate any possible pointer type!

6 Some pointer arithmetic int *a, *b; a++; or b--; a += 3; or b -= 5; But the only pointer-pointer operation allowed is pointer subtruction (use it for pointers of the same type): a-b We can also compare pointers: a>b

7 Getting an array of numbers #include void main() { int *numbers, size, i, sum = 0; printf( "How many numbers? " ); scanf( "%d", &size ); numbers = malloc( size * sizeof( int )); for( i = 0; i < size; i++ ) { scanf( "%d", &numbers[i] ); } for( i = 0; i < size; i++ ) { sum += numbers[i]; } printf( "%d\n", sum ); free( numbers ); }

8 Self-referential structures A structure that has as its element(s) pointers to the structure itself is called a self-referential structure. E.g. a tree: typedef struct tree { DATA d; struct tree *left, *right; } tree; Other classical structures include: stacks, queues and linked lists…

9 Linear Linked Lists Problem with arrays: If we assume that they’re of fixed length, need to know maximum length ahead of time. Unrealistic. Also, even if we did know the maximum length ahead of time, if array was not full, we would be “wasting memory.” One solution: Linear linked lists. #define NULL 0 typedef char DATA; struct linked_list { DATA d; struct linked_list *next; /* refers to self */ }; typedef struct linked_list ELEMENT; typedef ELEMENT *LINK;

10 Linear Linked Lists: List creation /* Uses recursion. From Kelley/Pohl. */ LINK string_to_list( char s[] ) { LINK head; if( s[0] == ‘\0’ ) return NULL; else { head = malloc( sizeof( ELEMENT )); head->d = s[0]; head->next = string_to_list( s + 1 ); return head; }

11 Linear Linked Lists: Counting int count( LINK head ) /* recursively: Kelley/Pohl */ { if( head == NULL ) return 0; else return( 1 + count( head->next )); } int count_it( LINK head ) { int cnt; for( cnt = 0; head != NULL; head = head->next ) { cnt++; } return cnt; }

12 Linear Linked Lists: Lookup /* from Kelley/Pohl */ LINK lookup( DATA c, LINK head ) { if( head == NULL ) return NULL; else if( c == head->d ) return head; else return( lookup( c, head->next )); }

13 Linear Linked Lists: Insertion/Deletion /* from Kelley/Pohl */ /* Assumes q is a one-element list, and inserts it between p1 and p2, assumed to be consecutive cells in some list */ void insert( LINK p1, LINK p2, LINK q ) { p1->next = q; q->next = p2; } void delete_list( LINK head ) { if( head != NULL ) { delete_list( head->next ); free( head ); }

14 Stacks Another form of data abstraction: will implement using ideas similar to those used in implementing linear linked list. Only two basic operations defined on a stack: push (insertion), pop (deletion). Access is restricted to the “head” of the stack. #define NULL 0 typedef char DATA; struct stack { DATA d; struct stack *next; /* refers to self */ }; typedef struct stack ELEMENT; typedef ELEMENT *LINK;

15 Stacks: Testing for emptiness, Top element int isempty( TOP t ) { return( t == NULL ); } DATA vtop( TOP t ) { return( t -> d ); }

16 Stacks: Pop /* remove top element from the stack */ void pop( TOP *t, DATA *x ) { TOP t1 = *t; if( !isempty( t1 )) { *x = t1->d; *t = t1->next; free( t1 ); } else printf( “Empty stack.\n” ); }

17 Stacks: Push /* put an element at the top of the stack */ void push( TOP *t, DATA x ) { TOP temp; temp = malloc( sizeof( ELEMENT )); temp->d = x; temp->next = *t; *t = temp; }

18 Comma Operator Has lowest precedence from any operator in C E.g. a=1, b=2 Will evaluate from left to right and has the value and type of the right most assignment Commas separating function arguments variables in declarations, etc. are not comma operators and do not guarantee left- to-right evaluation order…

19 Chapters covered from K&R Chapter 1 (all except 1.10) Chapter 2 Chapter 3 Chapter 4 (only ) Chapter 5 ( ) Chapter 6 (all except 6.9)