הגדרת משתנים יום שלישי 27 נובמבר 2018

Slides:



Advertisements
Similar presentations
Programming in C Chapter 10 Structures and Unions
Advertisements

Structures Often we want to be able to manipulate logical entities as a whole For example, complex numbers, dates, student records, etc Each of these must.
C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
Structures Spring 2013Programming and Data Structure1.
1 CSE 303 Lecture 12 structured data reading: Programming in C Ch. 9 slides created by Marty Stepp
Exercise 11 Dynamic allocation, structures, linked lists.
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.
Exercise 11 Dynamic allocation and structures. Dynamic Allocation Array variables have fixed size, used to store a fixed and known amount of variables.
1 ES 314 Advanced Programming Lec 3 Sept 8 Goals: complete discussion of pointers discuss 1-d array examples Selection sorting Insertion sorting 2-d arrays.
1 Structures, Dynamic Memory Allocation. 2 Agenda Structures Definition & usage Pointers to structures Arrays and pointers in structures Dynamic Memory.
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
Pointers| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2006 Slide 1 Pointers by Jumail Bin Taliba Faculty of Computer.
S-1 University of Washington Computer Programming I Lecture 18: Structures © 2000 UW CSE.
הגדרת משתנים יום שישי 18 ספטמבר 2015 יום שישי 18 ספטמבר 2015 יום שישי 18 ספטמבר 2015 יום שישי 18 ספטמבר 2015 יום שישי 18 ספטמבר 2015 יום שישי 18 ספטמבר.
Functions, Pointers, Structures Keerthi Nelaturu.
1 Structures. Structure (struct) Definition A Structure is a container, it can hold a bunch of things. –These things can be of any type. Structures are.
Learners Support Publications Classes and Objects.
COP Structures Instructor: Diego Rivera-Gutierrez I’m back baby!
Structures Combining data types into a logical groupings.
 Structures are like arrays except that they allow many variables of different types grouped together under the same name. For example you can create.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 13: Data structures in C.
APS105 Lists. Structures Arrays allow a collection of elements –All of the same type How to collect elements of different types? –Structures; in C: struct.
C Programming - Structures. Structures containing arrays A structure member that is an array does not ‘behave’ like an ordinary array When copying a structure.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 5.
1 Structures. 2 What is a Structure? Used for handling a group of logically related data items  Examples: Student name, roll number, and marks Real part.
Struct s (7.4) Used as data aggregates for an entity can be different types of data e.g. for student id, name, GPA, address,... Similar to classes, but.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
1 11/30/05CS150 Introduction to Computer Science 1 Structs.
13/10/2016CS150 Introduction to Computer Science 1 Multidimensional Arrays  Arrays can have more than one column  Two dimensional arrays have two columns.
1 Structures. 2 What is a Structure? Used for handling a group of logically related data items  Examples: Student name, roll number, and marks Real part.
הגדרת משתנים יום שלישי 14 יוני 2016 יום שלישי 14 יוני 2016 יום שלישי 14 יוני 2016 יום שלישי 14 יוני 2016 יום שלישי 14 יוני 2016 יום שלישי 14 יוני 2016.
Introduction We will study how to broaden the modeling facilities of C by defining our own data types that represent structured collections of data pertaining.
C Structures and Memory Allocation
Stack and Heap Memory Stack resident variables include:
Lesson #8 Structures Linked Lists Command Line Arguments.
Linked List :: Basic Concepts
CS1010 Programming Methodology
Hassan Khosravi / Geoffrey Tien
Chapter 19 Data Structures
CS1010 Programming Methodology
TMF1414 Introduction to Programming
CS150 Introduction to Computer Science 1
EECE.2160 ECE Application Programming
14th September IIT Kanpur
Lecture 9 Structure 1. Concepts of structure Pointers of structures
Structures.
Array of Structures A structure holds only one record But a record
Derived types.
Structures.
EKT150 : Computer Programming
Arrays and Arrays as Parameters
C Programming Strings.
EECE.2160 ECE Application Programming
Classes and Objects.
Structures vol2.
Linked List.
Programming Structures.
EECE.2160 ECE Application Programming
Functions.
EECE.2160 ECE Application Programming
Submitted By : Veenu Saini Lecturer (IT)
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
READING AND PRINTING MATRICES (with functions)
EECE.2160 ECE Application Programming
Chapter 11 Structure and Union Types.
EECE.2160 ECE Application Programming
Structures, Unions, and Enumerations
Introduction to Pointers
Presentation transcript:

הגדרת משתנים יום שלישי 27 נובמבר 2018 Department of Computer Science-BGU יום שלישי 27 נובמבר 2018

typedef השימוש ב - typedef typedef משמשת כדי להגדיר טיפוסים חדשים בשפה . התחביר : typedef <known type> <identifier>; מיקום הגדרות ה - typedef הינו בד"כ מעל הפונקציה main. לדוגמא: typedef int distance ; typedef double weight ; משלב זה בתוכנית הצהרות על משתנים כ - weight יהיו שקולות להצהרות כ - double . כנ"ל לגבי distance ו- int. Department of Computer Science-BGU יום שלישי 27 נובמבר 2018

Example #include <stdio.h> typedef double distance ; void main(void){ distance miles , kmeters ; scanf("%lf", &miles); kmeters = miles * 1.609 ; printf("%.2f miles = %.2f kmeters\n", miles , kmeters ); } עבור קלט 2 נקבל את הפלט : 2.00 miles = 3.22 kilometers Department of Computer Science-BGU יום שלישי 27 נובמבר 2018

Example אפשר להשתמש ב - typedef בכדי להגדיר טיפוסים חדשים כמערכים: #define N 10 #define M 20 typedef double vector[M] ; typedef double matrix[N][M] ; הגדרנו שני טיפוסים חדשים : vector ו - matrix . vector הוא טיפוס של מערך חד-ממדי בגודל Mשכל איבר בו הוא double ו-matrix הוא טיפוס של מערך דו-ממדי בגודל NM שכל איבר בו הוא double . משלב זה נוכל להגדיר מערכים חד-ממדיים כנ"ל באמצעות הטיפוס vector ומערכים דו-ממדיים כנ"ל באמצעות הטיפוס matrix . לדוגמא : vector a , b ; /* a & b are both arrays dimension M */ matrix mat ; /* mat is a two-dimensions array NM */ Department of Computer Science-BGU יום שלישי 27 נובמבר 2018

Structures Department of Computer Science-BGU יום שלישי 27 נובמבר 2018

Structures Often we want to be able to manipulate ‘logical entities’ as a whole For example, complex numbers, dates, student records, etc’ Each of these must be composed of more than one variable, but are logically units A struct (short for structure) is a collection of variables of different types, gathered into one super-variable It is used to define more complex data types Variables in a struct are called members or fields Department of Computer Science-BGU יום שלישי 27 נובמבר 2018

Example – complex numbers. The following is the definition of a new ‘variable’ of type complex number: struct complex { int real; int img; }; Once we define a structure, we can treat it as any type. In a program, we can then write: struct complex num1, num2, num3; Department of Computer Science-BGU יום שלישי 27 נובמבר 2018

Example – complex numbers. The following is the definition of a new ‘variable’ of type complex number: struct complex { int real; int img; }; Once we define a structure, we can treat it as any type. In a program, we can then write: struct complex num1, num2, num3; Department of Computer Science-BGU יום שלישי 27 נובמבר 2018

Example 2 מבנים הינם טיפוסים נגזרים לייצוג קבוצה של טיפוסים הומוגניים או הטרוגניים. לדוגמא ההגדרה הבאה : struct triple { double x ; int y ; char c ; } ; בהגדרה זו הגדרנו טיפוס חדש בשם struct triple שהינו מורכב משלושה משתנים x , y ו- c . המילה struct הינה מילה שמורה . הגדרת משתנים מהטיפוס החדש שיצרנו מתבצעת struct triple first , second ; Department of Computer Science-BGU יום שלישי 27 נובמבר 2018

Example 2 (cont.) כך הגדרנו שני משתני חדשים בשם first ו- second להיות משתנים מטיפוס struct triple . הגישה לאיברי (שדה) המבנה מתבצעת באמצעות האופרטור '.' ( נקודה ) . למשל :   first.x הינו השדה x במשתנה first . first.c הינו השדה c במשתנה first . second.y הינו השדה y במשתנה second . דוגמא לשימוש במבנה : void main() { struct triple a ;   scanf("%lf%d%c",&a.x,&a.y,&a.c); printf("x=%.2lf , y=%d , c=%c\n",a.x,a.y,a.c);  } Department of Computer Science-BGU יום שלישי 27 נובמבר 2018

Using typedef struct person { char name[N] , address[M]; long id ; int age , status ; } ; typedef struct person _t{ } person; typedef struct person_ t person; struct person _t{ המכללה האקדמית להנדסה סמי שמעון יום שלישי 27 נובמבר 2018

איתחול של מבנה ניתן לבצע איתחול של מבנהץ כדוגמא במבנה : struct person { char name[N] , address[M]; long id ; int age , status ; } ; איתחול: struct person person1= {“Haim Cohen”,”Dimona”, 012345678, 34, 2}; struct person class[2] = {{“Yaakov Cohen”,”Lahavim”, 012000678, 56, 1}, {“Cohen OneTwo”,”Meitar”, 012333678, 44, 2}}; המכללה האקדמית להנדסה סמי שמעון יום שלישי 27 נובמבר 2018

Exercise Implement the MultComplex function – Input - two complex numbers Output – their multiplication Note - If x=a+ib and y=c+id then: z = xy = (ac-bd)+i(ad+bc) Write a program that uses the above function to multiply two complex numbers given by the user Department of Computer Science-BGU יום שלישי 27 נובמבר 2018

פתרון typedef struct complex{ double x,y; }complex; complex * mult_comp(complex a, complex b){ complex * z = (complex *)malloc(sizeof(complex)); z->x = a.x * b.x – a.y * b.y; z->y = a.x * b.y + a.y * b.x; return z; } Department of Computer Science-BGU יום שלישי 27 נובמבר 2018

Miscellaneous structure trivia Structure members may be ordinary variable types, but also other structures and even arrays ! Structures can therefore be rather large and take up a lot of space ! Many times we prefer to pass structures to functions by address, and not by value. Thus a new copy of the structure is not created – just a pointer to the existing structure Department of Computer Science-BGU יום שלישי 27 נובמבר 2018

Nested structures typedef struct{ char name[30]; char address[50]; char phone_num[15]; } Supplier ; typedef struct { int max; int min; int curr; }Inventory; char name[30]; Supplier supplier; char department[15]; Inventory inventory; } Item ; Department of Computer Science-BGU יום שלישי 27 נובמבר 2018

More trivia Structures cannot be compared using the == operator They must be compared member by member Usually this will be done in a separate function Structures can be copied using the = operator Member-wise copy Department of Computer Science-BGU יום שלישי 27 נובמבר 2018

Exercise Write a struct that represents a date (day, month, year) Write a function that increments the date void IncDate(Date *d); For example – 31.12.05 -> 1.1.06 Department of Computer Science-BGU יום שלישי 27 נובמבר 2018

Structures containing arrays A structure member that is an array does not ‘behave’ like an ordinary array. When copying a structure that contains a member which is an array, the array is copied element by element Not just the address gets copied. Reminder – ordinary arrays can’t be copied simply by using the ‘=‘ operator. They must be copied using a loop. Department of Computer Science-BGU יום שלישי 27 נובמבר 2018

Structures containing arrays The same happens when passing the structure to a function Changing the array inside the function won’t change it in the calling function Reminder – when passing an ordinary array to a function, all that gets passed is the address of its first element Hence every change to the array within the function, changes the array in the calling function Department of Computer Science-BGU יום שלישי 27 נובמבר 2018

Pointer to structure מבנה הוא סוג משתנה רגיל מרגע הגדרתו ולכן ניתן ליצור משתנה בצורה דינמית, נניח : typedef struct stam{ int value; }item; ניתן להגדיר : item * ptr; ptr = (item *) malloc(sizeof(item); עכשיו אנו משנים את האופרטור להגיע לכל שדה בתוך המבנה: scanf*(“%d”, &(ptr->value)); Department of Computer Science-BGU יום שלישי 27 נובמבר 2018

Access structure members If A is of some structure with a member named x, then A.x is that member of A struct complex C; C.real = 0; If A is a pointer to a structure with a member x, then A->x is that member of the variable pointed by A. This is simply shorthand for - (*A).x struct complex *pc = &C; pc->real = 1; Department of Computer Science-BGU יום שלישי 27 נובמבר 2018

Pointers are another matter If the member is a pointer, for example to a dynamically allocated array, all that gets copied is the pointer (the address) itself Hence, we should take extra care when manipulating structures that contain pointers Department of Computer Science-BGU יום שלישי 27 נובמבר 2018

Pointers in structure typedef struct stam{ char name[80]; char * p_name; int value; }item; Problems: Must malloc; Copy , only the address Delete , first the allocations Department of Computer Science-BGU יום שלישי 27 נובמבר 2018