lecture_23 - ECE 190 Lecture 23 Structures in C Lecture...

Info iconThis preview shows pages 1–10. Sign up to view the full content.

View Full Document Right Arrow Icon
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 4
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 6
Background image of page 7

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 8
Background image of page 9

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 10
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: ECE 190 Lecture 23 Structures in C Lecture Topics struct typedef arrays of structs Lecture materials Textbook §19.1-19.3 Homework Machine problem MP4.2 due 4/14 Announcements April 12, 2011 V. Kindratenko ECE 190 Lecture 23 April 12, 2011 Review of data types in C 0 3 fundamental data types 0 int —— integer number 0 float/double- real number 0 char — character 0 real-world objects are mapped into these 3 fundamental types 0 we also introduced arrays and pointers o arrays allow to treat a group of values of the same type 0 pointers allow to point to objects of the fundamental data types 0 both pointers and arrays, including strings, are all derived from these basic data types 0 C language provides a support for describing real—world objects in terms of aggregations of their properties 0 Arrays is one such aggregation mechanism 0 Structure, which is a combination of several basic types, is yet another such aggregation mechanism Structures in C 0 Example: a repository of students and their grades in this class 0 Student characteristics/properties that we want to capture I Name, can be captured as an array of chars (string): char name [100] ; I Student ID, can be stored as an int: int ID; I Grade for the class, can be stored as a char: char grade; I There may be many other characteristics that we would want to capture.. 0 How do we capture all these properties? I If we only have one student, we can declare one variable per property: 0 char name [100]; 0 int ID; 0 char grade; "if we have many (N) students, we can allocate arrays: 0 char name [N] [100]; 0 int ID [N] ; 0 char grade [N] ; I to access information about a particular student, we would need to access data in all three arrays: name [i] , ID[i] , grade [1] o if there are only a few properties that we care about, this solution (using separate arrays) may be acceptable 0 but if we have many properties, the solution with arrays becomes cumbersome I think about passing a large number of arguments to a function 0 a better solution is to aggregate all the properties into a single object 2 V. Kindratenko l l, ). i i i i l l l ECE 190 Lecture 23 April 12, 2011 0 Structure is the way to aggregate several characteristics of a real-world object and threat them as one entity 0 struct construct allows to create a new data type consisting of several member elements 0 struct studentStruct { char name[100]; int ID; char grade; }; o mflmemmmdumhweawmdamwdflawmaMgwenmemg studentStruct; 0 To declare a variable of this type, we can use the new data type’s name: I struct studentstruct st; 0 This variable declaration results in the allocation of memory in the run-time stack to store all 3 member elements as if we would of stored all 3 of them separately: name[100] ID grade 0 individual member elements (members) of this structure can be accessed using the following syntax: I st . name - st.ID = 12345; I st . grade = ‘A’ 1 0 Here st refers to the name of the variable (aggregation) 7 and . grade , . ID, . name refer to an individual member/filed in the aggregation 0 Summary 0 Structure declaration syntax: I struct [tag] { <typel> <memberl>; <typeN> <memberN>; } [identifiers]; I tag provides a handle for referring to the structure later in the code I the list of members defines the organization of a structure 3 V. Kindratenko ECE190 Lecture 23 April 12, 2011 I we can optionally include identifiers in the structure’s declaration to actually declare variables of that structu re’s type 0 variable declaration of type struct: O O I struct <tag> <varName>; I here we declared a variable of type struct <tag> structure member access: I <varName>.<memberl>; struct construct allows to declare a new data type. The declare a variable fo this data type, we use "struct tag” as the data type name in the variable declaration. - C allows to give names to user-defined data types using typedef keyword. This, we can give anahenmfivebhonednameto”struct tag% 0 typedef struct tag myType; myType <varName>; 0 here old name “struct tag” will be given a new name myType. - Few examples: 0 O struct studentstruct { /* declare a new data type */ char name[lOO]; int ID; char grade; }; typedef struct studentstruct student; /* give it a name */ student 31, $2; /* declare variables of this data type */ scanf(“%s %d %c”, sl.name, &sl.ID, &sl.grade); /* use it */ printf(“%s %d %c”, sl.name, sl.ID, sl.grade); struct pixelTag { /* declare a new data type */ int r, g, b; }; typedef struct pixelTag pixel; /* give it a new name */ pixel p; /* declare a variable of this new type */ p.r = p.g = p.b = O; fprintf(f, “% %d %d\n”, p.r, p.g, p.b); /* use it */ struct _sphere_ { float x, y, 2; float r; 4 V. Kindratenko ECE 190 Lecture 23 April 12, 2011 float vx, vy, vz; }; typedef struct _sphere_ sphere; sphere balll, ballZ; Structure initialization can be done at the time of variable declaration: 0 student 31 = { “Bob”, 1234, ‘A’ }; o pixelp={0, O, O }; o sphere balll = { 1.0, 2.0, 1.0, 10.0, —l.0, -l.0, 4.0 }; Things you can(not) do with structs: 0 student sl, s2; 51 + 52 is both meaningless and syntactically not correct; 51 . ID + 32 . ID is permitted, but still meaningless; if (31 . grade > s2 . grade) — permitted 52 = 31 - assignment is permitted; Arrays of structs 0 student 31 - good enough to contain info about a single student. But what if we want to contain info about all students in this class? 0 This can be done by declaring an array of elements of type student: I student ece190 [250]; I this declaration resulted in allocating an array of 250 objects of type student I ece190 array works the same way as any other array declared using basic data types, e.g.: 0 ece190[0]; /* first element of the array */ ece190[1]; /* second element of the array */ I to refer to an individual field/member of a given element of the array, we W 'W'Wcombine array index syntax with struct member access syntax: 0 ece190 [0] .name [0] = ‘B’ ece190 [0] .name [1] = ‘o’ ece190 [0] .name [2] = ‘b' ece190 [0] .name [3] = ‘\0' ece190 [0] . ID = 12345; ece190 [O] . grade = ‘A’ Pointers and structs 0 As with other C data types, we can create pointers to structures: I student *ptr; 5 V. Kindratenko i i l l i l l i , i i i l l i ECE 190 Lecture 23 April 12, 2011 0 Example I student *ptr; student ecel90i250]; student sl; 1) ptr = &sl; /* pointer to $1 variable */ 2) ptr = &ece190[lO]; /* pointer to 111m element */ 3) ptr = ecel90; /* pointer to the entire array */ xFOOO $1 xFOF1 ece190[0] xFFOO ece190[10] ece190[249] 1) ptr = xFOOO ) pt, 2) ptr = xFFOO 5 3) ptr = xFOFl o amaflgfiwdnmmhmvhammmr I Synmx:(*<pointer name >).<member name> I Example: 0 (*ptr).name (*ptr).ID (*ptr).grade I There is a shortcut for this somewhat cumbersome syntax: l i l l g l i l o <pointer name >—><member name> 0 Here —> operator enables access to a member in struct given by pointer Wrerww I Example: 0 ptr—>name l ptr—>ID { ptr—>grade l Example Write a program that asks user to enter information about ECE190 students and stores this information inafibondbk #include <stdlib.h> #include <stdio.h> #define NofS 250 6 I V. Kindratenko ECE 190 Lecture 23 struct studentStruct { char name[100]; int ID; char grade; }; typedef struct studentStruct Student; void enterStudénts(Student s, int n); void writeStudentsToFile(Student s, int n, Char *fname); int main() { Student ece190[NofS]; enterStudents(ecel90, NofS); 'writestudentsToFile(ecel90, NofS, "ecel90.dat"); return 0; } void enterStudents(Student s, int n) { int i; char temp[8]; for (i = 0; i < n; i++) { printf("Enter student's name: "); gets(s[i].name); printf("Enter student's ID: "); scanf("%d", &(s[i].ID)); printf("Enter student's grade: "); scanf("\n%c", &(s[i].grade)); gets(temp); } April 12, 2011 void writeStudentsToFile(Student s, int n, char *fname) { FILE *f; int i; if ((f = fopen(fname, "w")) == NULL) { fprintf(stderr, "Unable to open file %s\n", fname); exit(l); } for (i = 0; i < n; i++) fprintf(f, "%s %d %c\n", s[i].name, s[i].ID, s[i].grade); fclose(f); V. Kindratenko Quwlrw dewlg Olav vow - . 23. pg “Qwa Wag/rm. item 9 R G ‘ ECE 190 Lecture 23 April 12, 2011 Union 0 a union data type is similar to a struct, however, it defines a single location in memory that can be given many different names 0 Example: 0 union valueUnion { long int i_value; float f_value; union valueUnion v; v.i_value = 5; /* holds integer */ v.f_value = 5.25f; /* now holds float */ /* but not both! */ Enumerated data type 0 Enumerated data type is used when a variable contains only a limited set of values. An enumeration consists of a set of named integer constants, called enumeration set; count starts from O. 0 Avafiabk\NnhenumerafiontypesuresoneofthevaMesoftheenunmrafionsetdefinedby that type. 0 Synwxzenum [tag] { enumerator—list } [identifier]; ; 0 Example: 0 enum week_day { SUN, MON, TUE, WED, THU, FRI, SAT }; enum week_day today; today = TUE; 0 here SUN equals 0, MON equals 1, and so on Value is implicitly set, but we can change it explicitly: o enum week_day { SUN=7, MON=1, TUE, WED, THU, FRI, SAT }; o in this case, SUN equals 7, MON equals 1, TUE equals 2, and so on 0 TNnkabmfithkasanakenmtwetothe#definepmpmmesordhmfiWe. l l 0 Another example: 0 enum BOOLEAN l { false, /* false = 0, true = 1 */ true i; typedef enum BOOLEAN bool; bool status; status = true; 8 V. Kindratenko ...
View Full Document

This note was uploaded on 01/22/2012 for the course ECE 191 taught by Professor Staff during the Spring '11 term at University of Illinois, Urbana Champaign.

Page1 / 10

lecture_23 - ECE 190 Lecture 23 Structures in C Lecture...

This preview shows document pages 1 - 10. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online