Structures, Pointers, Linked Lists

Similar documents
Cpt S 122 Data Structures. Data Structures

Subject: Fundamental of Computer Programming 2068

Introduction to Data Structures. Systems Programming

C Data Structures Stacks. Stack. push Adds a new node to the top of the stack

Assignment 6. Q1. Create a database of students using structures, where in each entry of the database will have the following fields:

Dynamic Memory Allocation

The combination of pointers, structs, and dynamic memory allocation allow for creation of data structures

Solution for Data Structure

PROGRAMMAZIONE I A.A. 2017/2018

Announcements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1

CSC 1600 Memory Layout for Unix Processes"

19-Nov CSCI 2132 Software Development Lecture 29: Linked Lists. Faculty of Computer Science, Dalhousie University Heap (Free Store)

JTSK Programming in C II C-Lab II. Lecture 3 & 4

CS61C Machine Structures. Lecture 4 C Structs & Memory Management. 9/5/2007 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

COMP26120: Linked List in C (2018/19) Lucas Cordeiro

Memory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables)

int marks[10]; // fixed size and fixed address No change in Memory address.

Cpt S 122 Data Structures. Course Review Midterm Exam # 1

Computer Systems and Networks

BBM 201 DATA STRUCTURES

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

Linked-List Basic Examples. A linked-list is Linear collection of self-referential class objects, called nodes Connected by pointer links

Dynamic Data Structures. CSCI 112: Programming in C

unsigned char memory[] STACK ¼ 0x xC of address space globals function KERNEL code local variables

Linked List in Data Structure. By Prof. B J Gorad, BECSE, M.Tech CST, PHD(CSE)* Assistant Professor, CSE, SITCOE, Ichalkaranji,Kolhapur, Maharashtra

Understanding Pointers

Pointers and Structure. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

EL2310 Scientific Programming

Variation of Pointers

All the above operations should be preferably implemented in O(1) time. End of the Queue. Front of the Queue. End Enqueue

dynamic memory allocation

CSCI-UA /2. Computer Systems Organization Lecture 19: Dynamic Memory Allocation: Basics

CS61C Machine Structures. Lecture 5 C Structs & Memory Mangement. 1/27/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

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

Outline. Computer programming. Usage of time and date functions. Date and Time: time.h. Date and Time: time.h. Time functions:

Single Dimension Arrays

Procedural programming with C

Computer programming. "An expert is a man who has made all the mistakes which can be made, in a narrow field." Niels Bohr

CS61C : Machine Structures

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

Introduction to C Language (M3-R )

Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

EL2310 Scientific Programming

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

CS113: Lecture 4. Topics: Functions. Function Activation Records

C Language Part 3. Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Fundamentals of Programming & Procedural Programming

Manual Allocation. CS 1622: Garbage Collection. Example 1. Memory Leaks. Example 3. Example 2 11/26/2012. Jonathan Misurda

Lists (Section 5) Lists, linked lists Implementation of lists in C Other list structures List implementation of stacks, queues, priority queues

Dynamic memory allocation

Memory Management. CSC215 Lecture

Dynamic Data Structures (II)

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

Outline. Briefly review the last class Pointers and Structs Memory allocation Linked lists

Top of the Stack. Stack ADT

Arrays Arrays and pointers Loops and performance Array comparison Strings. John Edgar 2

CSE 124 Discussion (10/3) C/C++ Basics

Class Information ANNOUCEMENTS

Data Structures and Algorithms for Engineers

Self-referential Structures and Linked List. Programming and Data Structure 1

Intermediate Programming, Spring 2017*

United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017

CS61C : Machine Structures

Run Time Environment

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type

Quick review pointer basics (KR ch )

Dynamic Memory Management. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013

However, in C we can group related variables together into something called a struct.

Pointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays

CS 222: Pointers and Manual Memory Management

Low-Level C Programming. Memory map Pointers Arrays Structures

EM108 Software Development for Engineers

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

Dynamic memory allocation (malloc)

CS61C : Machine Structures

CS261: HOMEWORK 2 Due 04/13/2012, at 2pm

Write a program that creates in the main function two linked lists of characters and fills them with the following values:

CS24 Week 2 Lecture 1

ENEE 150: Intermediate Programming Concepts for Engineers Spring 2018 Handout #27. Midterm #2 Review

Recitation 2/18/2012

mith College Computer Science CSC270 Spring 2016 Circuits and Systems Lecture Notes, Week 11 Dominique Thiébaut

MODULE V: POINTERS & PREPROCESSORS

ECE264 Spring 2014 Exam 2, March 11, 2014

Contents. A Review of C language. Visual C Visual C++ 6.0

In Java we have the keyword null, which is the value of an uninitialized reference type

MTH 307/417/515 Final Exam Solutions

#3. (Recursion) Write a recursive function to compute f(x) = f(x - 1) + f(x - 2) with f(0) = 0 and f(1) = 1.

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

ECE 2400 Computer Systems Programming Fall 2018 Topic 6: C Dynamic Allocation

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

CS 241 Data Organization Binary Trees

Pointers, Dynamic Data, and Reference Types

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS

BBM#101# #Introduc/on#to# Programming#I# Fall$2013,$Lecture$12$

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

Transcription:

Lecture 6: Structures, Pointers, Linked Lists Reminder: Pointers and structures Pointers to structures Dynamic memory allocation: malloc Linked lists Ordered linked lists Double linked lists, Trees

Reminder: Pointers Pointers are address-variables. They contain information about where another variable can be found in the memory (the variable they point at). Pointers are useful when working with arrays and as function arguments. 0x5000 array[0] int i, array[5]; int *arr_ptr; arr_ptr = array; for (i=0; i<5; ++i) printf\( %d, *\(arr_ptr+i)); int number; scanf\( %d,&number\); (array_ptr+3) 0x5003 0x5001 0x5002 0x5003 0x5004 array[1] array[2] array[3] array[4] Address of operator (&) pointer dereference (*)

Reminder: Structures struct can be used to define new structures struct emp_record { char name[30]; integer emp_id; integer age; ; struct emp_record emp1, emp2; emp1.age = 31; emp2.name = John Smith ; struc can be used as return value and arguments in functions You can also define arrays of struct struct emp_record postgrad[100];... postgrad[17].name = John Smith ;

Pointers to structures You can also define pointers to structures struct emp_record *emprec_ptr; (*emprec_ptr\).name = John Smith ; more efficient for function calls ( is not copied)

Pointers to structures You can also define pointers to structures struct emp_record *emprec_ptr; (*emprec_ptr\).name = John Smith ; more efficient for function calls ( is not copied) (*emprec_ptr).name can also be written as emprec_ptr->name struct emp_record *emprec_ptr; emprec_ptr->name = John Smith ;

Pointers to structures You can also define pointers to structures struct emp_record *emprec_ptr; (*emprec_ptr\).name = John Smith ; more efficient for function calls ( is not copied) (*emprec_ptr).name can also be written as emprec_ptr->name struct emp_record *emprec_ptr; emprec_ptr->name = John Smith ; A struct can also contain fields that are pointers (even pointers to another struct of the same kind) struct _node { char [100]; struct _node *next_node; linked list

malloc dynamic memory allocation Data is stored in two different areas of memory: stack and heap static; allocated at time of function call; deallocated when function is terminated dynamic; allocated on demand; persists for duration of the program

malloc dynamic memory allocation Data is stored in two different areas of memory: stack and heap static; allocated at time of function call; deallocated when function is terminated dynamic; allocated on demand; persists for duration of the program static: int a[100]; allocates 100x4 bytes in stack and calls it a

malloc dynamic memory allocation Data is stored in two different areas of memory: stack and heap static; allocated at time of function call; deallocated when function is terminated dynamic; allocated on demand; persists for duration of the program static: int a[100]; allocates 100x4 bytes in stack and calls it a dynamic: #include<stdlib.h> #include<stdio.h> int dim; int *a_ptr; scanf\( %d,&dim\); a_ptr = malloc(sizeof(int)*dim);... free(a_ptr); a_ptr = NULL;

malloc dynamic memory allocation Data is stored in two different areas of memory: stack and heap static; allocated at time of function call; deallocated when function is terminated dynamic; allocated on demand; persists for duration of the program static: int a[100]; allocates 100x4 bytes in stack and calls it a dynamic: malloc allocates the #include<stdlib.h> specified number of bytes in #include<stdio.h> heap memory and returns a int dim; generic pointer to it. int *a_ptr; scanf\( %d,&dim\); a_ptr = malloc(sizeof(int)*dim);... free(a_ptr); a_ptr = NULL;

malloc dynamic memory allocation Data is stored in two different areas of memory: stack and heap static; allocated at time of function call; deallocated when function is terminated dynamic; allocated on demand; persists for duration of the program static: int a[100]; allocates 100x4 bytes in stack and calls it a dynamic: #include<stdlib.h> #include<stdio.h> int dim; int *a_ptr; scanf\( %d,&dim\); a_ptr = malloc(sizeof(int)*dim);... malloc allocates the specified number of bytes in heap memory and returns a generic pointer to it. free deallocates the memory assigned to a_ptr free(a_ptr); a_ptr = NULL;

malloc dynamic memory allocation Data is stored in two different areas of memory: stack and heap static; allocated at time of function call; deallocated when function is terminated dynamic; allocated on demand; persists for duration of the program static: int a[100]; allocates 100x4 bytes in stack and calls it a dynamic: #include<stdlib.h> #include<stdio.h> int dim; int *a_ptr; scanf\( %d,&dim\); a_ptr = malloc(sizeof(int)*dim);... malloc allocates the specified number of bytes in heap memory and returns a generic pointer to it. free deallocates the memory assigned to a_ptr free(a_ptr); a_ptr = NULL; Heap memory can only be accesses via pointers (no named variables)!

malloc: example #include<stdio.h> #include<stdlib.h> main() { int dim, i; int *a_ptr; srand(time(null)); /* initializes random number generator */ printf("specify array dimension: "); scanf("%d", &dim); /* now use malloc to allocate the correct amount of memory */ a_ptr = (int*) malloc(sizeof(int)*dim); /* Assign pseudo-random numbers to the elements of the array */ for (i=0; i < dim; ++i) a_ptr[i] = rand() % 100 + 1; /* Now print out the array */ for (i=0; i < dim; ++i) printf("a_ptr[%d] = %d\n", i, *(a_ptr+i)); return(0);

#include<stdio.h> #include<stdlib.h> main() { int dim, i; int *a_ptr; malloc: example http://www.tcd.ie/physics/people/claude.ederer/teaching/3c01/use_malloc.c srand(time(null)); /* initializes random number generator */ printf("specify array dimension: "); scanf("%d", &dim); /* now use malloc to allocate the correct amount of memory */ a_ptr = (int*) malloc(sizeof(int)*dim); /* Assign pseudo-random numbers to the elements of the array */ for (i=0; i < dim; ++i) a_ptr[i] = rand() % 100 + 1; /* Now print out the array */ for (i=0; i < dim; ++i) printf("a_ptr[%d] = %d\n", i, *(a_ptr+i)); return(0); Exercise: Modify program so that it also calculates the a verage o ver all values of a_ptr.

Linked lists Idea: Each element of the list contains a pointer to the next element first_ptr 3 17 99 NULL

Linked lists Idea: Each element of the list contains a pointer to the next element first_ptr 3 17 99 NULL Adding a new element at the beginning of the list: struct linked_list { int ; struct linked_list *; ; struct linked_list *first_ptr = NULL; void add_list(int number) { struct linked_list *new_item_ptr; new_item_ptr = malloc(sizeof(struct linked_list)); new_item_ptr-> = number; new_item_ptr-> = first_ptr; first_ptr = new_item_ptr;

Linked lists Idea: Each element of the list contains a pointer to the next element first_ptr 3 17 99 NULL Adding a new element at the beginning of the list: struct linked_list { int ; struct linked_list *; ; struct linked_list *first_ptr = NULL; void add_list(int number) { struct linked_list *new_item_ptr; new_item_ptr = malloc(sizeof(stru ct linked_list)); new_item_ptr-> = number; new_item_ptr-> = first_ptr; first_ptr = new_item_ptr;

Linked lists Idea: Each element of the list contains a pointer to the next element first_ptr 3 17 99 NULL 8 Adding a new element at the beginning of the list: struct linked_list { int ; struct linked_list *; ; struct linked_list *first_ptr = NULL; void add_list(int number) { struct linked_list *new_item_ptr; new_item_ptr = malloc(sizeof(stru ct linked_list)); new_item_ptr-> = number; new_item_ptr-> = first_ptr; first_ptr = new_item_ptr;

Linked lists Idea: Each element of the list contains a pointer to the next element first_ptr 3 17 99 NULL 8 Adding a new element at the beginning of the list: struct linked_list { int ; struct linked_list *; ; struct linked_list *first_ptr = NULL; void add_list(int number) { struct linked_list *new_item_ptr; new_item_ptr = malloc(sizeof(stru ct linked_list)); new_item_ptr-> = number; new_item_ptr-> = first_ptr; first_ptr = new_item_ptr;

Linked lists Idea: Each element of the list contains a pointer to the next element NULL first_ptr 3 17 99 8 Adding a new element at the beginning of the list: struct linked_list { int ; struct linked_list *; ; struct linked_list *first_ptr = NULL; void add_list(int number) { struct linked_list *new_item_ptr; new_item_ptr = malloc(sizeof(stru ct linked_list)); new_item_ptr-> = number; new_item_ptr-> = first_ptr; first_ptr = new_item_ptr;

An example #include<stdlib.h> #include<stdio.h> struct linked_list { int ; struct linked_list *; ; struct linked_list *first_ptr = NULL; /* Function to add a list element */ void add_list(int number) { struct linked_list *new_item_ptr; new_item_ptr = malloc(sizeof(struct linked_list)); new_item_ptr-> = number; new_item_ptr-> = first_ptr; first_ptr = new_item_ptr; return; /* Function to print out list */ void print_list() { struct linked_list *current_ptr; current_ptr = first_ptr; while (current_ptr!= NULL){ printf("%d\n",current_ptr->); current_ptr = current_ptr->; return; main() { int value; while (1){ printf("enter number (0 to stop): "); scanf("%d", &value); if (value == 0) break; add_list(value); print_list(); return(0);

Example: Ordered list A function to create an ordered list of numbers (see: linked_list2.c) void enter_list(int number) { struct linked_list *before_ptr; struct linked_list *after_ptr; struct linked_list *new_item_ptr; before_ptr = first_ptr; if (before_ptr == NULL){ add_list(number); return; if (before_ptr-> >= number){ add_list(number); return; after_ptr = before_ptr->; while (1) { if (after_ptr == NULL) break; if (after_ptr-> >= number) break; after_ptr = after_ptr->; before_ptr = before_ptr->; new_item_ptr = malloc(sizeof(struct linked_list)); new_item_ptr-> = number; before_ptr-> = new_item_ptr; new_item_ptr-> = after_ptr; return;

Double-linked lists head_ptr NULL 19 8 32 NULL prev_ptr prev_ptr prev_ptr tail_ptr

Double-linked lists head_ptr NULL 19 8 32 NULL prev_ptr prev_ptr prev_ptr tail_ptr struct double_list { int ; struct double_list *; struct double_list *prev_ptr; ;

Double-linked lists head_ptr NULL 19 8 32 NULL prev_ptr struct double_list { int ; struct double_list *; struct double_list *prev_ptr; ; prev_ptr prev_ptr tail_ptr void add_head(int number){ struct double_list *new_item_ptr; new_item_ptr = malloc(sizeof(struct double_list)); new_item_ptr-> = number; new_item_ptr-> = head_ptr; head_ptr = new_item_ptr; */ /* now establish the backward links */ new_item_ptr->prev_ptr = NULL; if (new_item_ptr-> == NULL) /* First element tail_ptr = new_item_ptr; else new_item_ptr->->prev_ptr = new_item_ptr;

Double-linked lists head_ptr NULL 19 8 32 NULL prev_ptr struct double_list { int ; struct double_list *; struct double_list *prev_ptr; ; prev_ptr prev_ptr tail_ptr Try writing functions add_tail, print_fwd, print_bwd, enter (ordered double list)! void add_head(int number){ struct double_list *new_item_ptr; new_item_ptr = malloc(sizeof(struct double_list)); new_item_ptr-> = number; new_item_ptr-> = head_ptr; head_ptr = new_item_ptr; */ /* now establish the backward links */ new_item_ptr->prev_ptr = NULL; if (new_item_ptr-> == NULL) /* First element tail_ptr = new_item_ptr; else new_item_ptr->->prev_ptr = new_item_ptr;

Tree structures l_ptr r_ptr struct node { int ; struct node *l_ptr; struct node *r_ptr; ; l_ptr r_ptr l_ptr r_ptr Trees can be more efficient to search through Use recursion with trees But: important to create a well-balanced tree

Summary use malloc/free to dynamically allocate space in heap memory heap memory can only be accessed via pointers (no named variables) linked lists are dynamically growing/shrinking structures other structures: ordered lists, doubly linked lists, trees... entry pointer is needed (first_ptr, head_ptr, tail_ptr,...) take care not to lose links between list elements