Winter2015 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University C: Advanced Topics.

Slides:



Advertisements
Similar presentations
C: Advanced Topics-II Winter 2013 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University.
Advertisements

Pointers.
Computer Programming for Engineering Applications ECE 175 Intro to Programming.
Programming in C Chapter 10 Structures and Unions
Dynamic memory allocation
Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
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.
Pointers & Dynamic Memory Allocation Mugurel Ionu Andreica Spring 2012.
Dynamic Memory Allocation
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
Spring 2005, Gülcihan Özdemir Dağ Lecture 12, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 12 Outline 12.1Introduction.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Growing Arrays in C By: Victoria Tielebein CS 265- Spring 2011.
Agenda  Review: pointer & array  Relationship between pointer & array  Dynamic memory allocation.
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.
Introduction of Memory Allocation. Memory Allocation There are two types of memory allocations possible in c. Compile-time or Static allocation Run-time.
Kernighan/Ritchie: Kelley/Pohl:
Memory Allocation. Memory A memory or store is required in a computer to store programs (or information or data). Data used by the variables in a program.
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:
Dynamic memory allocation. The process of allocating memory at run time is known as dynamic memory allocation. C have four library functions for allocating.
Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University C: Formatted Files.
1 Day 03 Introduction to C. 2 Memory layout and addresses r s int x = 5, y = 10; float f = 12.5, g = 9.8; char c = ‘r’, d = ‘s’;
CSSE221: Software Dev. Honors Day 27 Announcements Announcements Projects turned in? Projects turned in? The 2 required Angel surveys are due by 9 pm tonight.
Structs. Structures We already know that arrays are many variables of the same type grouped together under the same name. Structures are like arrays except.
C: Advanced Topics Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
1 Programming with Pointers Turgay Korkmaz Office: SB Phone: (210) Fax: (210) web:
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
6. More on Pointers 14 th September IIT Kanpur C Course, Programming club, Fall
Winter 2015 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University C: Assignment-II Tips.
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
1 CS 132 Spring 2008 Chapter 3 Pointers and Array-Based Lists read p
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Introduction to Computer Organization & Systems Topics: C arrays C pointers COMP Spring 2014 C Part IV.
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
Topics memory alignment and structures typedef for struct names bitwise & for viewing bits malloc and free (dynamic storage in C) new and delete (dynamic.
ECE Application Programming Instructors: Dr. Michael Geiger & Nasibeh Nasiri Fall 2015 Lecture 31: Structures (cont.) Dynamic memory allocation.
Computer Programming for Engineering Applications ECE 175 Intro to Programming.
DATA STRUCTURE & ALGORITHMS Pointers & Structure.
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.
Sudeshna Sarkar, CSE, IIT Kharagpur1 Structure and list processing Lecture
C: Advanced Topics Winter 2013 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University.
1 Linked List. 2 List A list refers to a sequence of data items  Example: An array The array index is used for accessing and manipulation of array elements.
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.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
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.
C Structures and Memory Allocation
Dynamic Allocation Review Structure and list processing
Linked List :: Basic Concepts
Day 03 Introduction to C.
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
Day 03 Introduction to C.
Module 2 Arrays and strings – example programs.
Dynamic Memory Allocation
CS111 Computer Programming
Computing Science Thompson Rivers University
Dynamic Memory Allocation
EECE.2160 ECE Application Programming
C Programming Lecture-8 Pointers and Memory Management
Chapter 10-1: Dynamic Memory Allocation
Structures CSE 2031 Fall May 2019.
Structures EECS July 2019.
C Structures and Memory Allocation
Dynamic Data Structures
Presentation transcript:

Winter2015 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University C: Advanced Topics

Unit Learning Objectives TRU-COMP2130 C: Advanced Topics 2 Use pointers for dynamic memory management. Structures and unions Use open(), read(), write(), close(), and FILE* functions to manipulate files. Use user-defined data structures. More coming

Unit Contents TRU-COMP2130 C: Advanced Topics 3 1. Pointers and Arrays 2. Input and Output 3. Structures 4. Self Referential structures

TRU-COMP2130 C Programming 4 Dynamic memory management #include void *malloc(int size); // allocate size bytes // and return the addr void free(void *); // free the memory space... int *p, n; scanf(“%d”, &n); // space for n-many integer variables. p = (int*)malloc(sizeof(int) * n); p[0] = 10; *(p+1) = 20; *(p+2) = 30; p++; *p = 4;

Structures Introduction 5 It is a way to have a single name referring to a group of a related values. Structures provide a way of storing many different values in variables of potentially different types under the same name. its design makes things more compact. Structs are generally useful whenever a lot of data needs to be grouped together Example: a contact group may have {name, address, phone number, and mobile number} TRU-COMP2130

Example Introduction 6 struct database { int id_number; int age; float salary; }; int main() { struct database employee; /* There is now an employee variable that has modifiable variables inside it.*/ employee.age = 22; employee.id_number = 1; employee.salary = ; printf(“Employee ID = %d, Age = %d and Salary = %7.2f”, employee.id, employee.age, employee.salary); } TRU-COMP2130

2. Structures TRU-COMP2130 C: Advanced Topics 7 User-defined data structure struct student_rcd {// class without methods in Java intstudent_number; charname[128];... };... struct student_rcd record[10], *rp; struct student_rcd test;// how to declare a struct variable test.student_number = 10;// how to access a member print_rcd(test); read_rcd(&test); record[0].student_number = 5;

TRU-COMP2130 C: Advanced Topics 8 void print_rcd(struct student_rcd rcd) { printf(“Number: %d\n”, rcd.student_number); printf(“Name: %s\n”, rcd.name); // name is an array. // not &(rcd.name) } void read_rcd(struct student_rcd *rcd) { printf(“Enter number: “); scanf(“%d”, &(rcd->student_number)); // reference rqd printf(“Enter name: “); scanf(“%s”, rcd->name); // name is an array. // not &(rcd->name) }

Typedef TRU-COMP2130 C: Advanced Topics 9 typedef int Length; // Now Length is a data type. typedef char *String; // Now String is a data type. typedef struct tnode { /* the tree node: */ char *word; /* points to the text */ int count; /* number of occurrences */ struct tnode *left, *right; /* children */ struct tnode *parent; } Treenode; // Now Treenode is a data type.... Length len, maxlen; Length *lengths[]; String p, lineptr[MAXLINES]; Treenodetnode1;

Union TRU-COMP A union is a special data type available in C that enables you to store different data types in the same memory location like structures The main difference is that a union may have many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multi-purpose. #include union Data { int i; float f; char str[20]; }; int main( ) { union Data data; data.i = 10; printf( "data.i : %d\n", data.i); return 0; }

Self-Referential Structures TRU-COMP2130 C: Advanced Topics 11 struct tnode { /* the tree node: */ char word[50]; int count; struct tnode *next; /* next child */ }; struct tnode root; root.next = (struct tnode *)malloc(...);

Dynamic Memory Allocation TRU-COMP2130 C: Advanced Topics 12 struct Student { char name[128]; int number; Student *next; }; typedef struct Student Student; Student *head = null; // important Student *new, *tmp; new = create_student(); // create a record, read data from the user, // store them into the record add_student(head, new); // add the new record at the end of the list tmp = find_student(head, ); // find the record whose number is.. printf(“%d: %s\n”, tmp->number, tmp->name); // print the record delete_student(head, ); Name Number next Name Number next Name Number next Head null

Allocation functions TRU-COMP2130 Introduction 13 Malloc() Calloc() Free()

Malloc() TRU-COMP2130 Introduction 14 The name malloc stands for "memory allocation". The function malloc() reserves a block of memory of specified size and return a pointer of type void which can be casted into pointer of any form. Syntax of malloc() ptr=(cast-type*)malloc(byte-size) ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer. Example: ptr=(int*)malloc(100*sizeof(int)); will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the pointer points to the address of first byte of memory.

Calloc() TRU-COMP2130 Introduction 15 The name calloc stands for "contiguous allocation". The only difference between malloc() and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero. Syntax of calloc() ptr=(cast-type*)calloc(n,element-size); This statement will allocate contiguous space in memory for an array of n elements. Example: ptr=(float*)calloc(25,sizeof(float)); This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e, 4 bytes.

Free() TRU-COMP2130 Introduction 16 Dynamically allocated memory with either calloc() or malloc() does not get return on its own. The programmer must use free() explicitly to release space. syntax of free() free(ptr); This statement cause the space in memory pointer by ptr to be deallocated.

realloc TRU-COMP2130 Introduction 17 If the previously allocated memory is insufficient or more than sufficient. Then, you can change memory size previously allocated using realloc(). Syntax of realloc() ptr=realloc(ptr,newsize); Here, ptr is reallocated with size of newsize.

TRU-COMP2130 C: Advanced Topics create_student(... ) // create a record, read data from the user, { // store them into the record Student *new = (... )malloc(... ); scanf(“%s”,...) // read name scanf(“%d”,...) // read number new->next = null; // very important; (*new).next = null return...; };... add_student(... head,... new) // add the new record at the end of the list { Student *tmp; if (head == null) // when there is no record yet head = new; else { while((*tmp).next != null) // move to the last record tmp = (*tmp).next; // You cannot use array syntaxes (*tmp).next = new; // because the Student objects were not } // consecutively created. return; }

TRU-COMP2130 C: Advanced Topics find_student(... head,... no) // find the record { Student *tmp; tmp = head; while(tmp != null) { if ((... == no) break; tmp =...; }... delete_student(... head,... no) {... }