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

Similar documents
Structures. Basics of Structures (6.1) EECS l Now struct point is a valid type. l Defining struct variables: struct point { int x; int y; };

CS 11 C track: lecture 5

Contents. Custom data type struct data type Fixed length memory Alias data type

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

Kurt Schmidt. October 30, 2018

CS1100 Introduction to Programming

CS24 Week 2 Lecture 1

Dynamic Data Structures. CSCI 112: Programming in C

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

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

Arrays, Pointers and Memory Management

Low-Level C Programming. Memory map Pointers Arrays Structures

Character Strings. String-copy Example

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

Q1: /8 Q2: /30 Q3: /30 Q4: /32. Total: /100

Subject: Fundamental of Computer Programming 2068

Dynamically Allocated Memory in C

Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables.

Dynamic Memory Allocation

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

Dynamic Memory Allocation: Advanced Concepts

C Structures & Dynamic Memory Management

ECE 15B COMPUTER ORGANIZATION

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

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

Procedural programming with C

Quiz 0 Review Session. October 13th, 2014

Memory Allocation. General Questions

CS 33. Intro to Storage Allocation. CS33 Intro to Computer Systems XXVI 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.

Dynamic Memory Allocation

Heap Arrays. Steven R. Bagley

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

211: Computer Architecture Summer 2016

CS61C : Machine Structures

Week 9 Part 1. Kyle Dewey. Tuesday, August 28, 12

Pointers, Dynamic Data, and Reference Types

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

Department of Computer Science & Engineering Indian Institute of Technology Kharagpur. Practice Sheet #09. Topic: Structures in C Date:

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

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

Darshan Institute of Engineering & Technology for Diploma studies Unit 4

Structures. CSE 142 Programming I. Chapter 11. Review: Data Structures. Defining structs. Terminology. Structs: Heterogeneous Structures

Lecture 8 Dynamic Memory Allocation

NEXT SET OF SLIDES FROM DENNIS FREY S FALL 2011 CMSC313.

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

Programs in memory. The layout of memory is roughly:

EM108 Software Development for Engineers

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

Intermediate Programming, Spring 2017*

CSE2301. Dynamic memory Allocation. malloc() Dynamic Memory Allocation and Structs

Advanced Pointer Topics

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

CS61C : Machine Structures

Linked List. April 2, 2007 Programming and Data Structure 1

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

Pointers. Introduction

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

POINTER AND ARRAY SUNU WIBIRAMA

CS C Primer. Tyler Szepesi. January 16, 2013

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

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

CS61C : Machine Structures

Dynamic Memory Allocation II October 22, 2008

Dynamic memory allocation

Fall 2018 Discussion 2: September 3, 2018

C-types: basic & constructed. C basic types: int, char, float, C constructed types: pointer, array, struct

Arrays and Pointers (part 1)

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

CS113: Lecture 9. Topics: Dynamic Allocation. Dynamic Data Structures

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

Class Information ANNOUCEMENTS

ECE 2400 Computer Systems Programming Fall 2018 Topic 7: Concrete Data Types

CA341 - Comparative Programming Languages

Chapter 14. Dynamic Data Structures. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved.

DC54 DATA STRUCTURES DEC 2014

C Programming Language: C ADTs, 2d Dynamic Allocation. Math 230 Assembly Language Programming (Computer Organization) Thursday Jan 31, 2008

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

Structures and Pointers

Short Notes of CS201

Read: Kernighan & Ritchie

Understanding Pointers

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

These problems are provided to you as a guide for practice. The questions cover important concepts covered in class.

CS201 - Introduction to Programming Glossary By

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

SYSC 2006 C Winter 2012

C & Data Structures syllabus

Arrays and Pointers. CSE 2031 Fall November 11, 2013

CS 5513 Entry Quiz. Systems Programming (CS2213/CS3423))

Lectures 13 & 14. memory management

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

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

CP2 Revision. theme: dynamic datatypes & data structures

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

ME964 High Performance Computing for Engineering Applications

Lecture 5: Multidimensional Arrays. Wednesday, 11 February 2009

Memory Allocation III

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012

Transcription:

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

C Structures and Memory Allocation A struct is a data structure that comprises multiple types, each known as a member Example: A student may have members: name (char[ ]), age (int), GPA (float or double), sex (char), major (char[ ]), etc struct student { char name[20]; int age; ; Memory allocation If we want to create a structure that can vary in size, we will allocate the struct on demand and attach it to a previous struct through pointers

Recommended Struct Examples struct point { int x; int y; ; struct point p1, p2; p1 and p2 are both points, containing an x and a y value struct { int x; int y; p1, p2; p1 and p2 are both points containing an x and a y, but do not have a tag (struct type name) struct point { int x; int y; p1, p2; same as the other two versions, but united into one set of code, p1 and p2 have the tag point union a { int x; struct { int x; int y; ; unnamed struct, no instance

Accessing structs A struct is much like an array The structure stores multiple data To access a particular member, you use the. operator as in student.firstname or p1.x and p1.y we will see later that we will also use - > to reference a field if the struct is pointed to by a pointer To access the struct itself, use the variable name Legal operations on the struct are assignment, taking its address with &, copying it, and passing it as a parameter Point p1 = {5, 10; // same as p1.x = 5; p1.y = 10; only works when declaring p1 p1 = p2; // same as p1.x = p2.x; p1.y = p2.y;

structs as Parameters Passing as a parameter: void foo(struct point x, struct point y) { Returning a struct: struct point createpoint(int a, int b) { struct point temp; temp.x = a; temp.y = b; return temp;

Inputting a struct in a Function We will need to do multiple inputs for our struct let s write a separate function to input all the values into our struct The code to the right does this #include <stdio.h> struct point { int x; int y; ; void getstruct(struct point); void output(struct point); void main( ) { struct point y = {0, 0; getstruct(y); output(y); void getstruct(struct point p) { scanf("%d", &p.x); scanf("%d", &p.y); printf("%d, %d", p.x, p.y); void output(struct point p) { printf("%d, %d", p.x, p.y);

This doesn't work Results: Input two numbers: 10 10 10, 10 0, 0 Why? C uses pass by copy the struct is copied into the function so that p in the function is different from y in main after inputting the values into p, nothing is returned, so y remains {0, 0

One Solution For Input In our previous solution, we passed the struct into the function and manipulated it in the function, but it wasn t returned What was passed into the function was a copy So structs differ from arrays! In our input function, we can instead create a temporary struct and return the struct rather than having a void function void main( ) { struct point y = {0, 0; y = getstruct( ); output(y); struct point inputpoint( ) { struct point temp; scanf( %d, &temp.x); scanf( %d, &temp.y); return temp;

Pointers to Structs The previous solution had two flaws: It required twice as much memory we needed 2 points, one in the input function, one in the function that called input It required copying each member of temp back into the members of the original struct with our point type, that s not a big deal because there were only two members, but this may be undesirable when we have a larger struct So instead, we might choose to use a pointer to the struct We see an example next, but first

Pointers to Structs struct foo { // a global definition, the struct foo is known in all of int a, b, c; // these functions ; foo fooinstance={1,2,3; foo* a=&fooinstance; fooinstance.a fooinstance.b Memory 1 2 Address 1084 1088 fooinstance.c a 3 1084 1092 1096 If a is a pointer to a struct, then to access the struct s members, we use (*a).x Or use the - > operator as in a->x

#include <stdio.h> struct foo { int a, b, c; ; // function prototypes void inp(struct foo *); void outp(struct foo); Pointer-based Example // a global definition, the struct foo is known in all of // these functions // both functions receive a pointer to a struct foo void main( ) { struct foo x; inp(&x); outp(x); // declare x to be a foo // get its input, passing a pointer to foo // send x to outp, this requires 2 copying actions void inp(struct foo *x) { // notice the notation here: &ptr->member scanf("%d%d%d", &x->a, &x->b, &x->c); void outp(struct foo x) // same notation, but without the & { printf("%d %d %d\n", x.a, x.b, x.c);

Nested structs with pointers In order to provide modularity, it is common to use alreadydefined structs as members of additional structs Recall our point struct, now we want to create a rectangle struct the rectangle is defined by its upper left and lower right points struct point { int x; int y; struct rectangle { struct point pt1; struct point pt2; struct rectangle r; Then we can reference r.pt1.x, r.pt1.y, r.pt2.x and r.pt2.y

Nested structs with pointers In order to provide modularity, it is common to use alreadydefined structs as members of additional structs Recall our point struct, now we want to create a rectangle struct the rectangle is defined by its upper left and lower right points struct point { int x; int y; struct rectangle { struct point pt1; struct point pt2; struct rectangle r; Then we can reference r.pt1.x, r.pt1.y, r.pt2.x and r.pt2.y Now consider the following struct rectangle r, *rp; rp = &r; Then the following are all equivalent r.pt1.x (*rp).pt1.x rp->pt1.x But not rp->pt1->x (since pt1 is not a pointer to a point)

typedef typedef is used to define new types The format is typedef description name; Where description is a current type or a structural description such as an array declaration or struct declaration Examples: typedef int Length; // Length is now equivalent to the type int struct node { // declares a node structure that contains int data; // a data item and a pointer to a struct of type node struct node *next; ; We can simplify our later uses of node by doing the following typedef struct node anode; // this allows us to refer to anode instead of struct node

Overview of memory management To this point, we have been declaring pointers and having them point at already created variables/structures Stack-allocated memory 15 When a function is called, memory is allocated for all of its parameters and local variables. Each active function call has memory on the stack (the current function call on top) When a function call terminates, the memory is deallocated ( freed up ) Ex: main() calls f(), f() calls g() g() recursively calls g() g() g() f() main()

Heap-allocated memory (Dynamic allocation) However, the primary use of pointers is to create dynamic structures Use heap allocation for persistant data The pointer can point to a piece of memory that has just been created (allocated) We will use this approach (memory allocation + pointers) to create data structures like linked lists g() Stack g() f() Heap main()

malloc and calloc The two primary memory allocation operations in c are malloc and calloc For most situations, we will use malloc: pointer = (type *) malloc(sizeof(type)); This sets pointer to point at a newly allocated chunk of memory that is the type specified and the size needed for that type NOTE: pointer will be NULL if there is no more memory to allocate The cast may not be needed, but is good practice calloc has the form: pointer = (type *) calloc(n, sizeof(type)); // n is the size of the array calloc is usually used for the creation of an array Another C instruction is free, to free up the allocated memory when you no longer need it as in free(pointer);

calloc example #include <stdio.h> #include <stdlib.h> // needed for calloc void main() { int i; int *x, *y; // two pointers to int arrays x = (int *) calloc(10, sizeof(int)); // x now points to an array of 10 ints for(i=0;i<10;i++) x[i] = i; // fill the array with values // oops, need more room than 10 y = (int *) calloc(20, sizeof(int)); // create an array of 20, temporarily // pointed to by y for(i=0;i<10;i++) y[i] = x[i]; // copy old elements of x into y free(x); // release memory of old array for(i=10;i<20;i++) y[i] = i; // add the new elements x = y; // reset x to point at new, bigger array

Linked Structures Our last topic is in building linked structures lists, trees, graphs These are dynamic structures, when you want to add a node, you allocate a new chunk of memory and attach it to the proper place in the structure via the pointers In linked lists, the pointer is a next pointer to the next node in the list, in a tree, there are left and right children pointers We will use malloc to allocated the node We will need to traverse the structure to reach the proper place to insert a new node

Declarations for Nodes struct node { int data; struct node *next; ; node *front=null; front is a pointer to the first node in a linked list. It may initially be NULL. Traversing our linked list might use code like this: temp = front; while(temp!=null) { // process temp temp=temp->next; struct treenode { int data; struct treenode *left; struct treenode *right; ; Our root node will be declared as treenode *root; It is common in trees to have the root node point to the tree via the right pointer only with the left pointer remaining NULL

Declarations for Nodes struct node { int data; struct node *next; ; node *front=null; front is a pointer to the first node in a linked list. It may initially be NULL. Traversing our linked list might use code like this: temp = front; while(temp!=null) { // process temp temp=temp->next; struct treenode { int data; struct treenode *left; struct treenode *right; ; Our root node will be declared as treenode *root; It is common in trees to have the root node point to the tree via the right pointer only with the left pointer remaining NULL

Linked Lists NULL struct node* front=null; front A linked list is a series of connected nodes Each node contains at least A piece of data (any type) Pointer to the next node in the list front: pointer to the first node The last node points to NULL node struct node struct node { int data; struct node *next; ; data int next struct node*

front Linked Lists A linked list is a series of connected nodes Each node contains at least A piece of data (any type) Pointer to the next node in the list front: pointer to the first node The last node points to NULL 2 NULL front=(struct node) malloc(sizeof(struct node)); front->data=2; front->next=null; node struct node struct node { int data; struct node *next; ; data int next struct node*

Linked Lists 2 4 3 NULL front A linked list is a series of connected nodes Each node contains at least A piece of data (any type) Pointer to the next node in the list front: pointer to the first node The last node points to NULL node struct node struct node { int data; struct node *next; ; data int next struct node*

Inserting a new node Node* InsertNode(int index, double x) Steps 1. Locate index th element 2. Allocate memory for the new node 3. Point the new node to its successor 4. Point the new node s predecessor to the new node index th element

Inserting a new node Node* InsertNode(int index, double x) Steps 1. Locate index th element 2. Allocate memory for the new node 3. Point the new node to its successor 4. Point the new node s predecessor to the new node index th element newnode