Structures in C

Views:
 
Category: Education
     
 

Presentation Description

REpresenting Data structures in C language.

Comments

Presentation Transcript

PowerPoint Presentation:

Structures in C 1

PowerPoint Presentation:

2 Data Structures ( struct ) Arrays require that all elements be of the same data type. Many times it is necessary to group information of different data types. An example is a materials list for a product. The list typically includes a name for each item, a part number, dimensions, weight, and cost. C and C++ support data structures that can store combinations of character, integer floating point and enumerated type data. They are called a structs .

PowerPoint Presentation:

There is no class in C, but we may still want non-homogenous structures So, we use the struct construct struct for structure A struct is a data structure that comprises multiple types, each known as a member each member has its own unique name and a defined type Example: A student may have members: name (char[ ]), age (int), GPA (float or double), sex (char), major (char[ ]), etc If we want to create a structure that can vary in size, we will allocate the struct on demand and attach it to a previous struct through pointers Here, we examine structs, allocation techniques, and linked structures 3 Structures ( struct )

PowerPoint Presentation:

4 Structures ( struct ) A struct is a derived data type composed of members that are each fundamental or derived data types. A single struct would store the data for one object. An array of struct s would store the data for several objects. A struct can be defined in several ways as illustrated in the following examples:

The struct Definition:

The struct Definition struct is a keyword for defining a structured declaration Format: name represents this structure’s tag and is optional we can either provide name or after the } we can list variables that will be defined to be this structure We can also use typedef to declare name to be this structure and use name as if it were a built-in type typedef will be covered later in these notes struct name { type1 name1; type2 name2; … }; name1 and name2 are members of name 5

PowerPoint Presentation:

6 Declaring Structures (struct) Reserves Space struct my_example { int label; char letter; char name[20]; } mystruct ; Does Not Reserve Space struct my_example { int label ; char letter ; char name[20] ; } ; /* The name "my_example" is called a structure tag */

Examples:

Examples struct point { int x; int y; }; struct point p1, p2; p1 and p2 are both points, containing an x and a y value struct { int x; int y; } p1, p2; p1 and p2 both have the defined structure, containing an x and a y, but do not have a tag struct point { int x; int y; } p1, p2; same as the other two versions, but united into one set of code, p1 and p2 have the tag point For the first and last sets of code, point is a defined tag and can be used later (to define more points, or to declare a type of parameter, etc) but in the middle code, there is no tag, so there is no way to reference more examples of this structure 7

PowerPoint Presentation:

A struct is much like an array The structure stores multiple data You can access the individual data, or you can reference the entire structure To access a particular member, you use the . operator as in student.firstName or p1.x and p1.y we will see later that we will also use - > to reference a field if the struct is pointed to by a pointer To access the struct itself, reference it by the variable name Legal operations on the struct are assignment, taking its address with &, copying it, and passing it as a parameter p1 = {5, 10}; // same as p1.x = 5; p1.y = 10; p1 = p2; // same as p1.x = p2.x; p1.y = p2.y; 8 Accessing Struct Members

PowerPoint Presentation:

9 Accessing Struct Members Individual members of a struct variable may be accessed using the structure member operator (the dot, “.”): mystruct . letter ; Or , if a pointer to the struct has been declared and initialized Some_name *myptr = &mystruct ; by using the structure pointer operator (the “->“): myptr -> letter ; which could also be written as: (*myptr) . letter ;

structs as Parameters:

structs as Parameters We may pass structs as parameters and functions can return structs Passing as a parameter: void foo(struct point x, struct point y) {…} notice that the parameter type is not just the tag, but preceded by the reserved word struct Returning a struct: struct point createPoint(int a, int b) { struct point temp; temp.x = a; temp.y = b; return temp; } 10

Inputting a struct in a Function:

Inputting a struct in a Function We will need to do multiple inputs for our struct Rather than placing all of the inputs in main, let’s write a separate function to input all the values into our struct The code to the right does this But how do we pass back the struct? Remember C uses pass by copy the struct is copied into the function so that p in the function is different from y in main after inputting the values into p, nothing is returned and so y remains {0, 0} #include <stdio.h> struct point { int x; int y; }; void getStruct(struct point); void output(struct point); void main( ) { struct point y = {0, 0}; getStruct(y); output(y); } void getStruct(struct point p) { scanf("%d", &p.x); scanf("%d", &p.y); printf("%d, %d", p.x, p.y); } void output(struct point p) { printf("%d, %d", p.x, p.y); } 11

One Solution For Input:

One Solution For Input In our previous solution, we passed the struct into the function and manipulated it in the function, but it wasn’t returned Why not? Because what was passed into the function was a copy, not a pointer So structs differ from arrays as structs are not pointed to In our input function, we can instead create a temporary struct and return the struct rather than having a void function struct point inputPoint( ) { struct point temp; scanf(“%d”, &temp.x); scanf(“%d”, &temp.y); return temp; } void main( ) { struct point y = {0, 0}; y = getStruct( ); output(y); } We could also pass the address of y and treat the struct like an array, we will see this next, but it requires a change in how we handle the members of the struct 12

Pointers to Structs:

Pointers to Structs The previous solution had two flaws: It required twice as much memory we needed 2 points, one in the input function, one in the function that called input It required copying each member of temp back into the members of the original struct with our point type, that’s not a big deal because there were only two members, but this may be undesirable when we have a larger struct So instead, we might choose to use a pointer to the struct, we pass the pointer, and then we don’t have to return anything – scanf will follow the pointer and place the datum in our original struct We see an example next, but first… If a is a pointer to a struct, then to access the struct’s members, we use the - > operator as in a->x 13

Pointer-based Example:

Pointer-based Example #include <stdio.h> struct foo { // a global definition, the struct foo is known in all of int a, b, c; // these functions }; // function prototypes void inp(struct foo *); // both functions receive a pointer to a struct foo void outp(struct foo); void main( ) { struct foo x; // declare x to be a foo inp(&x); // get its input, passing a pointer to foo outp(x); // send x to outp, this requires 2 copying actions } void inp(struct foo *x) { // notice the notation here: &ptr->member scanf("%d%d%d", &x->a, &x->b, &x->c); } void outp(struct foo x) // same notation, but without the & { printf("%d %d %d\n", x.a, x.b, x.c); } 14

Nested structs:

Nested structs In order to provide modularity, it is common to use already-defined structs as members of additional structs Recall our point struct, now we want to create a rectangle struct the rectangle is defined by its upper left and lower right points Now consider the following struct rectangle r, *rp; rp = &r; Then the following are all equivalent r.pt1.x rp->pt1.x (r.pt1).x (rp->pt1).x But not rp->pt1->x (since pt1 is not a pointer to a point) struct point { int x; int y; } struct rectangle { struct point pt1; struct point pt2; } If we have struct rectangle r; Then we can reference r.pt1.x, r.pt1.y, r.pt2.x and r.pt2.y 15

Arrays of structs:

Arrays of structs To declare an array of structs (once you have defined the struct): struct rectangle rects[10]; rects now is a group of 10 structures (that consist each of two points) You can initialize the array as normal where each struct is initialized as a { } list as in {5, 3} for a point or {{5, 3}, {8, 2}} for a rectangle The array of structs will be like the array of classes that we covered in 260/262, we will use this data structure if we want to create a database of some kind and apply such operations as sorting and searching to the structure 16

Example:

Example struct point{ int x int y; }; struct rectangle { struct point p1; struct point p2; }; void printRect(struct rectangle r) { printf("<%d, %d> to <%d, %d>\n", r.p1.x, r.p1.y, r.p2.x, r.p2.y); } void main( ) { int i; struct rectangle rects[ ] = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}; // 2 rectangles for(i=0;i<2;i++) printRect(rects[i]); } 17

PowerPoint Presentation:

18 Sample Program With Structs /* This program illustrates creating structs and then declaring and using struct variables. Note that struct personal is an included data type in struct "identity". */ #include <stdio.h> struct person //Create a struct but don’t reserve space. { long id; float gpa; } ; struct identity //Create a second struct that includes the first one. { char name[30]; struct personal person; } ;

PowerPoint Presentation:

19 Sample Program With Structs (cont.) int main ( ) { struct identity js = {"Joe Smith"}, *ptr = &js ; js.person.id = 123456789 ; js.person.gpa = 3.4 ; printf ("%s %ld %f\n", js.name, js.person.id, js.person.gpa) ; printf ("%s %ld %f\n", ptr->name, ptr->person.id, ptr->person.gpa) ; }

authorStream Live Help