1 / 24

הגדרת משתנים

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

tirzah
Download Presentation

הגדרת משתנים

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. הגדרת משתנים Department of Computer Science-BGU

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

  3. 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

  4. 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

  5. Structures Department of Computer Science-BGU

  6. 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

  7. 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

  8. 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

  9. 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

  10. 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

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

  12. איתחול של מבנה ניתן לבצע איתחול של מבנהץ כדוגמא במבנה : 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}}; המכללה האקדמית להנדסה סמי שמעון

  13. 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

  14. פתרון 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

  15. 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

  16. Nested structures typedef struct{           char           name[30];      char           address[50];           char           phone_num[15];           } Supplier ; typedef struct {           int max;           int min;           int curr; }Inventory;   typedef struct {           char           name[30];           Supplier   supplier;           char           department[15];           Inventory inventory;    } Item ; Department of Computer Science-BGU

  17. 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

  18. Exercise • Write a struct that represents a date (day, month, year) • Write a function that increments the datevoid IncDate(Date *d); • For example – 31.12.05 -> 1.1.06 Department of Computer Science-BGU

  19. 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

  20. 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

  21. 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

  22. 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

  23. 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 carewhen manipulating structures that contain pointers Department of Computer Science-BGU

  24. 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

More Related