Computers and programming The 6 th lecture Jiří Šebesta.

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

Pointers.
A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
Computer Programming for Engineering Applications ECE 175 Intro to Programming.
Programming in C Chapter 10 Structures and Unions
Data Structure Lecture-3 Prepared by: Shipra Shukla Assistant Professor Kaziranga University.
C Language.
Senem Kumova Metin Spring2009 STACKS AND QUEUES Chapter 10 in A Book on C.
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.
Dynamic Memory Allocation (also see pointers lectures) -L. Grewe.
Programming Languages and Paradigms The C Programming Language.
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.
Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
Kernighan/Ritchie: Kelley/Pohl:
Winter2015 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University C: Advanced Topics.
Computers and programming The 7 th lecture Jiří Šebesta.
Linked Lists. Array Limitations Arrays have a fixed size that cannot be changed at run time What if your program had an array to store info regarding.
Introduction to C Programming CE Lecture 18 Dynamic Memory Allocation and Ragged Arrays.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 10 - C Structures, Unions, Bit Manipulations,
Pointers| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2006 Slide 1 Pointers by Jumail Bin Taliba Faculty of Computer.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Computers and programming The 3 rd lecture Jiří Šebesta.
C Tokens Identifiers Keywords Constants Operators Special symbols.
Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation.
Computers and programming 1 The 11 th lecture Jiří Šebesta.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Dynamic memory allocation and Pointers Lecture 4.
1 CS 132 Spring 2008 Chapter 3 Pointers and Array-Based Lists read p
1 Pointers to structs. 2 A pointer to a struct is used in the same way as a pointer to a simple type, such as an int. Pointers to structs were introduced.
16. STRUCTURES, UNIONS, AND ENUMERATIONS. Declaring Structures A structure is a collection of one or more components (members), which may be of different.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Introduction to Data Structures Systems Programming Concepts.
 Structures are like arrays except that they allow many variables of different types grouped together under the same name. For example you can create.
Data Structure and c K.S.Prabhu Lecturer All Deaf Educational Technology.
Derived Types C allows a number of derived types: –Array - group of similar elements (same type) –Pointer - location of a variable –Enumerated - set of.
Pointers. Pointer Variable Declarations and Initialization Pointer variables – Contain memory addresses as their values – Normal variables contain a specific.
C Lecture Notes 1 Structures & Unions. C Lecture Notes Introduction Structures –Collections of related variables (aggregates) under one name Can.
Chapter 10 Structures, Unions, Bit Manipulations, and Enumerations Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering.
Generic lists Vassilis Athitsos. Problems With Textbook Interface? Suppose that we fix the first problem, and we can have multiple stacks. Can we have.
1 CSC103: Introduction to Computer and Programming Lecture No 24.
Computer Programming for Engineering Applications ECE 175 Intro to Programming.
1 EPSII 59:006 Spring HW’s and Solutions on WebCT.
Structures. Outline Introduction Structure Definitions and declarations Initializing Structures Operations on Structures members Structures as Functions.
CSC Programming for Science Lecture 34: Dynamic Pointers.
CNG 140 C Programming (Lecture set 12) Spring Chapter 13 Dynamic Data Structures.
1 Lecture10: Structures, Unions and Enumerations 11/26/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
Sudeshna Sarkar, CSE, IIT Kharagpur1 Structure and list processing Lecture
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
What do I need to Know For My Assignment?. C Pointer Review To declare a pointer, we use the * operator. This is similar to but different from using *
Pointers. Pointer Fundamentals  When a variable is defined the compiler (linker/loader actually) allocates a real memory address for the variable. –int.
Lecture 10: Structures. Outline Introduction Structure Definitions and declarations Initializing Structures Operations on Structures members Structures.
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.
Dynamic Allocation Review Structure and list processing
CSCI206 - Computer Organization & Programming
Programming Languages and Paradigms
Dynamic Memory Allocation
Govt. Polytechnic,Dhangar
EECE.2160 ECE Application Programming
Dynamic Memory A whole heap of fun….
Introduction to Computer Organization & Systems
Dynamic Memory A whole heap of fun….
C Programming Lecture-8 Pointers and Memory Management
Variables in C Topics Naming Variables Declaring Variables
Presentation transcript:

Computers and programming The 6 th lecture Jiří Šebesta

TOPIC 1.Structures 2.Unions 3.Enumerative type 4.Dynamic variables - introduction 5.Example

Structures (1/4) Structure: an array consisting of items of different types embedding into superior type typedef struct friends // my girlfriend { char fname[20]; // her first name char sname[20]; // her surrname int age; // her age char phone[20]; // her phone number } T_friend; Declaration type identifier

Structures (2/4) int main(void) { T_friend baby; strcpy(baby.fname, "Anna\0"); strcpy(baby.sname, "Novakova\0"); baby.age = 16; strcpy(baby.phone, " \0"); printf(" %s %s - %d let - tel.: %s", baby.fname, baby.sname, baby.age, baby.phone); getchar(); return 0; } Access to item of structure: Source code: Ex59.c variableitem

Structures (3/4) typedef struct date // date { int year; // year int month; // month int day; // day } T_date; typedef struct drivelog // drive log book { char driver[20]; // name char in_city[20];// initial city char en_city[20];// ending city T_date in_date; // initial date T_date en_date; // ending dta int dist; // distance int in_tacho; // initial st. of tacho. int en_tacho; // ending st. of tacho. } T_drivelog; Structure in structure:

Structures (4/4) T_drivelog toyota020, toyota021; strcpy(toyota020.driver, "John"); toyota020.in_date.year = 2011; toyota020.in_tacho = 53210; toyota020.en_tacho = 53372; toyota020.dist = toyota020.en_tacho-toyota020.in_tacho; strcpy(toyota021.driver, "Judith"); strcpy(toyota021.in_city, toyota020.en_city); toyota021.in_tacho = toyota020.en_tacho; toyota021.en_tacho = 53712; toyota021.dist = toyota021.en_tacho-toyota021.in_tacho; Manipulation with items of structure: Source code: Ex60.c

Unions (1/3) Union: it enables to save values of different types to a single variable (allocated common space in memory) union u1 {int i; double d; char c;} U = {'u'}; name of union list of union items variable of declared type of unie Memory size allocated for the union is given by the size of the largest element STRUCTURE: int and double and char UNION: int or double or char

Unions (2/3) typedef union id // ID of item { int id_num; // numerical ID char id_str[10]; // textual ID } T_id; int main(void) { char input_id[10]; int n, t; printf("\n\nInsert ID: "); gets(input_id);// get string from stdin … Declaration type identifiervariable of declared type

Unions (3/3) t=0; // test if at least char is not digit for(n=0; input_id[n]!='\0'; n++) if (input_id[n] '9') t=1; // t=0 input_id is a number, t=1 input_id is a string if (t==0)// input_id is a number { item.id_num=atol(input_id); printf("ID contents a number: %d\n", item.id_num); } else// input_id is a string { strcpy(item.id_str, input_id); printf("ID contents a string: %s\n", item.id_str); } S. code: Ex61.c

Enumerative type (1/3) Enumerative type: a set of symbolic constants with strictly defined values enum cards {seven, eight, nine, face_card, ace} set_1, set_2; enum cards {seven=7, eight, nine, face_card=20, ace=30} set_1, set_2; Declaration: type identifiervariable of declared type

Enumerative type (2/3) Operator for enumerative type: – only assignment enum cards {seven=7, eight, nine, face_card=20, ace=30} set_1, set_2; set_1 = nine; set_2 = 8; //not possible, 8 isn’t enumerator set_1 -=2; //not possible int num = seven //type cast of enumerator seven to int

Enumerative type (3/3) enum zodiac {aries,taurus,gemini,cancer,leo,virgo, libra, scorpio, sagittarius, capricorn, …} eva; eva = virgo; switch(eva) { case aries: printf(”She is hard-headed”); break; case taurus: printf(”She is reserved”); break; case gemini: printf(”She is friendly”); break; case cancer: printf(”She is anxious”); break; case leo: printf(”She is bossy”); break; case virgo: printf(”She is trusty”); break; case libra: printf(”She is shaky”); break; … } Source code: Ex62.c

Dynamic variables – intro (1/3) Static variable: – memory space allocation when program is starting – memory space release when program is closing Dynamic variable: – controlled memory space allocation when program is running by function malloc() in C – controlled memory space release when program is running by function free() in C

Dynamic variables – intro (2/3) Application of dynamic variables: – a memory space can be allocated and released if program is running any time – suited for large blocks of data (e.g. large arrays), which are temporal (e.g. results, which will not be used later) – if we work with unknown size of array, if we use a static variable, we have to allocate the space for the worst case (max. size), e.g. double x[10000], this space is permanently blocked (in given function)

Dynamic variables – intro (3/3) #include int main( void) { double *x, y; x = (double*)malloc(sizeof(double)); *x = 3.14; y = *x; free(x); printf("Ludolf's number: %f", y); printf("Ludolf's number: %f", *x); //free(x); getchar(); return 0; } free address free variable void *malloc(size_t size) type cast space release in memory pointed by x this space in a memory is pointed by x allocation of space in a memory with size of double Source code: Ex63.c

Example (1/5) Create a program working as a car database. Each car is described by a type and a year of production. Data of cars are saved in dynamic variables, pointers are stored in an array. Adding a car is activated by pressing the key A, deleting by pressing D, and the program is stopped by pressing Q. In the database, at least one car has to be left. #include typedef struct car // car record { char type[10]; int year; } T_car; T_car *my_cars[20]; // ptrs. to cars - global int cnt=0; // recorded cars - global

void addcar(char *atype, int ayear) { T_car *car; // pointer to a car car = (T_car*)malloc(sizeof(T_car)); strcpy(car->type, atype); // notation 1 (*car).year = ayear; // notation 2 my_cars[cnt++] = car; } Example (2/5) void showdelcar(void) { printf("type: %s\n", my_cars[cnt]->type); printf("year: %d\n", my_cars[cnt]->year); } Function which adds a car Function which displays erased car

void erasecar(void) { if(cnt>1) // if at least two cars { cnt--; // one car to be removed showdelcar(); // print the removed car free(my_cars[cnt]); // delete last } else printf("All cars can’t be deleted"); } Example (3/5) Function which deletes a car

int main(void) { char cmd, my_type[12]; int my_year; printf("\nA: Add, D: Delete, Q: Quit\n"); scanf("%c", &cmd); fflush( stdin); while(!(cmd == 'Q' || cmd == 'q')) { if(cmd=='A' || cmd=='a') { printf("\ntype : "); scanf("%s", &my_type); fflush(stdin); printf("\nyear : "); scanf("%d", &my_year); fflush(stdin); add(my_type, my_year); } Example (4/5) Main function - beginning

if( cmd=='D' || cmd=='d') erasecar(); printf("\nA: Add, D: Delete, Q: Quit"); scanf("%c", &cmd); fflush(stdin); } return 0; } Example (5/5) Main function - conclusion Source code: Ex64.c

TOPIC OF THE NEXT LECTURE Programming with files THANK YOU FOR YOUR ATTENTION