1 Structs. 2 Defining a Structure Often need to keep track of several pieces of information about a given thing. Example: Box We know its length width.

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

Introduction to C Programming
Programming in C Chapter 10 Structures and Unions
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.
1 Structures. 2 User-Defined Types C provides facilities to define one’s own types. These may be a composite of basic types ( int, double, etc) and other.
Pointer Variables The normal variables hold values. For example, int j; j = 2; Then a reference to j in an expression will be identified with the value.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
Programming and Data Structure
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.
Structures Spring 2013Programming and Data Structure1.
Structures in C.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Destructors Math 130 Lecture # xx Mo/Da/Yr B Smith: New lecture for 05. Use this for evolving to Java B Smith: New lecture for 05. Use this for evolving.
C and Data Structures Baojian Hua
Programming in C Pointer Basics.
Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Pointer Data Type and Pointer Variables
8. Structures, File I/O, Recursion 18 th October IIT Kanpur 1C Course, Programming club, Fall 2008.
Engineering Computing I Chapter 6 Structures. Sgtructures  A structure is a collection of one or more variables, possibly of different types, grouped.
Functions, Pointers, Structures Keerthi Nelaturu.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
CSE 232: C++ pointers, arrays, and references Overview of References and Pointers Often need to refer to another object –Without making a copy of the object.
Programming in C Structs and Unions. Java vs C Suppose you were assigned a write an application about points and straight lines in a coordinate plane.
C STRUCTURES. A FIRST C PROGRAM  #include  void main ( void )  { float height, width, area, wood_length ;  scanf ( "%f", &height ) ;  scanf ( "%f",
Week 9 - Monday.  What did we talk about last time?  Time  GDB.
1 Pointers and Strings Chapter 5 2 What You Will Learn...  How to use pointers Passing arguments to functions with pointers See relationship of pointers.
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.
Spring 2005, Gülcihan Özdemir Dağ Lecture 11, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 11 Outline 11.1.
1 Homework HW5 due today Review a lot of things about allocation of storage that may not have been clear when we covered them in our initial pass Introduction.
Engineering Problem Solving with C Fundamental Concepts Chapter 7 Structures.
Chapter 7 A Data Types – Structures Structures Structure: C++ construct that allows multiple variables to be grouped together Structure Declaration.
ECE 103 Engineering Programming Chapter 49 Structures Unions, Part 1 Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE.
A FIRST BOOK OF C++ CHAPTER 16 DATA STRUCTURES. OBJECTIVES In this chapter, you will learn about: Single Structures Arrays of Structures Structures as.
Homework Finishing K&R Chapter 5 today –Skipping sections for now –Not covering section 5.12 Starting K&R Chapter 6 next.
CS 261 – Data Structures C Pointers Review. C is Pass By Value Pass-by-value: a copy of the argument is passed in to a parameter void foo (int a) { a.
1 9/6/05CS360 Windows Programming CS360 Windows Programming.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
1 Homework / Exam Finishing K&R Chapter 5 today –Skipping sections for now –Not covering section 5.12 Starting K&R Chapter 6 next Continue HW5.
POINTERS Introduction to Systems Programming - COMP 1002, 1402.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Structures 142 S -1 What is a structure? It is a collection of possibly different types Name the collection Name the components For example: a student.
142 L -1 Pointers Chapter 6 C uses a call BY VALUE for functions for example: void add_one(int x, int y) { x=x+1; y=y+1; } int main(void) { int a,b; a=4;
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
CSE 251 Dr. Charles B. Owen Programming in C1 structs Aggregating associated data into a single variable Box width length height Circle radius int main()
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
Programming in C Arrays, Structs and Strings. 7/28/092 Arrays An array is a collection of individual data elements that is:An array is a collection of.
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
Data Structures in C++ Pointers & Dynamic Arrays Shinta P.
Structures CSE 2031 Fall March Basics of Structures (6.1) struct point { int x; int y; }; keyword struct introduces a structure declaration.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7. 12: Structures Starting Out with C++ Early Objects Eighth.
Chapter 6 Structures Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh University.
1 Structures & Unions. 2 User-Defined Types C provides facilities to define one’s own types. These may be a composite of basic types ( int, double, etc)
CS1010 Programming Methodology
Motivation and Overview
Chapter 5 Classes.
Class Operations Pointer and References with class types
CS1010 Discussion Group 11 Week 12 – Structured Structures.
Pointers.
Data Types – Structures
Data Types – Structures
Homework Finishing K&R Chapter 5 today Starting K&R Chapter 6 next
Initializing variables
Variables in C Topics Naming Variables Declaring Variables
Programming in C Pointer Basics.
EECE.2160 ECE Application Programming
Week 9 - Monday CS222.
Presentation transcript:

1 Structs

2 Defining a Structure Often need to keep track of several pieces of information about a given thing. Example: Box We know its length width height weight contents

3 Defining a Structure We could define a separate variable to hold each piece of information: int length; int width; int height; double weight; char contents[32]; If we wanted to pass the information to a function, it would have to have five parameters.

4 Function to do something regarding a box void box_func (int length, int width, int height, double weight, char contents[]) { /* Do something with a box. */... }

5 The C “struct” The C “struct” is a way to combine all of this information in a single package. Old style declaration and usage struct BOX { int length; int width; int height; double weight; char contents[32]; }; struct BOX box2; “tag name” New user defined type

6 The C “struct” The C “struct” is a way to combine all of this information in a single package. typedef struct BOX { int length; int width; int height; double weight; char contents[32]; } box_t; Optional “tag name” OK to omit New user defined type

7 We can declare variables of the newly defined struct type in either of two ways: struct BOX box2; box_t box1; Declaring struct variables Older form. Rarely used today. Newer form using the typedef. This is just a programming style convention. Not significant to the compiler and not required.

8 Members of a struct typedef struct BOX { int length; int width; int height; double weight; char contents[32]; } box_t; Members of the struct Members are declared within the struct just as local variables are declared within a function. No memory is allocated by the typedef Note style.

9 Members of a struct Members of a struct can be any previously defined type Including arrays Including other structs Including pointers

10 Declaring a struct variable In order to have the compiler allocate memory for a struct, we have to declare a variable of that type. box_t box1; We can initialize a struct with the declaration: box_t box1 = {24, 12, 12, 5.3, "Fine German Wine"};

11 How to access members of a struct To access a member, use the name of the struct variable “dot” name of the member box1.length box1.contents These expressions work like normal variable names. Note: box1 is the struct variable name, not the type name.

Accessing struct members #include typedef struct BOX { int length; int width; int height; double weight; char contents[32]; } box_t; int main (void) { int dimension_total; box_t box1 = {24, 12, 12, 5.3, "Fine German Wine"}; printf ("Length of box1 is %d\n", box1.length ); printf ("Box1 contains %s\n", box1.contents ); dimension_total = box1.length + box1.width + box1.height; printf ("Sum of the dimensions is %d\n", dimension_total); return 0; }

13 Accessing struct members

14 Accessing members with a pointer We often need to access members of a struct using a pointer to the struct. There is a new operator for this: -> Example: box_t* pBox1;... pBox1 = &box1; pBox1->length is the same as box1.length

15 Accessing members with a pointer Use the “arrow” to get at members using a pointer to the struct. Use the “dot” to get at members using the name of the struct.

16 Accessing members with a pointer typedef struct BOX { int length; int width; int height; double weight; char contents[32]; } box_t; int main (void) { int dimension_total; box_t box1 = {24, 12, 12, 5.3, "Fine German Wine"};

17 Accessing members with a pointer box_t* pBox1 = &box1; printf ("Length of box1 is %d\n", pBox1->length); printf ("Box1 contains %s\n", pBox1->contents); dimension_total = pBox1->length + pBox1->width + pBox1->height; printf ("Sum of the dimensions is %d\n", dimension_total); return 0; } Declare and initialize pointer to struct.

18 Accessing members with a pointer Question: Why don’t we use the * to dereference a pointer to a struct? Answer: We could. (*pBox1).length is the same thing as pBox1->length The parentheses are necessary. *pBox1.length gets a compile error

19 Accessing members with a pointer The “arrow” notation is just nicer syntax. (*pBox1).length is clunky! pBox1->length is easier to write and easier to read. Always use this form rather than the “dot” form when working with pointers to structs.

20 Using Structures We can do almost anything with structs that we can do with the built-in types. Assignment. Pass to a function. Return from a function. Create pointers to a struct. Create arrays of structs. Use a struct as element in another struct.

21 Using Structures The one major exception is comparison. We can’t say if (box1 == box2) box_t box1 = {24, 12, 12, 5.3, "Fine German Wine"}; box_t box2 = box1; if (box1 == box2) { printf ("box1 and box2 are equal\n"); } This gets a compile error.

22 Comparing Structures We have to check each member individually. box_t box1 = {24, 12, 12, 5.3, "Fine German Wine"}; box_t box2 = box1; if ((box1.length == box2.length) && (box1.width == box2.width ) && (box1.height == box2.height) && (box1.weight == box2.weight) && (strcmp(box1.contents, box2.contents) == 0)) { printf ("box1 and box2 are equal\n"); }

23 Passing a struct to a function void display_box ( box_t box ) { printf ("Box length is %d\n", box.length ); printf ("Box width is %d\n", box.width); printf ("Box height is %d\n", box.height); printf ("Box contains %s\n", box.contents); } int main () { box_t box1 = {24, 12, 12, 5.3, "Fine German Wine"}; display_box(box1); return 0; } box is effectively a local variable A copy of the box_t struct used as an argument by the caller. Used same as a local variable Just like passing an int to a function This is an example of “Call by Value”

24 Passing a struct to a function

25 Comparing Structures If you were going to be comparing box_t variables frequently, it would be convenient to define a function for this. int Box_Equal(box_t box1, box_t box2) { if ((box1.length == box2.length) && (box1.width == box2.width ) && (box1.height == box2.height) && (box1.weight == box2.weight) && (strcmp(box1.contents, box2.contents) == 0)) { return 1; } return 0; }

26 Passing a pointer to a struct to a function void display_box ( box_t* pBox ) { printf ("Box length is %d\n", pBox->length); printf ("Box width is %d\n", pBox->width); printf ("Box height is %d\n", pBox->height); printf ("Box contains %s\n", pBox->contents); } int main (void) { box_t box1 = {24, 12, 12, 5.3, "Fine German Wine"}; box_t* pBox1 = &box1; display_box (pBox1); return 0; } Function gets a pointer to a box struct in the caller’s scope. Use pointer to access members This is an example of “Call by Address”

27 Passing a pointer to a struct to a function In this case, the function can modify the caller’s struct. void shrink (box_t* pBox) { pBox->length = pBox->length/2; pBox->width = pBox->width/2; pBox->height = pBox->height/2; }

28 Passing a pointer to a struct to a function int main (void) { box_t box1 = {24, 12, 12, 5.3, "Fine German Wine"}; box_t* pBox1 = &box1; display_box (pBox1); shrink (pBox1); printf ("\nAfter call to shrink\n"); display_box (pBox1); return 0; }

29 Passing a pointer to a struct to a function

30 Returning a struct from a function box_t new_box (int size_param) { box_t box; box.length = size_param*3; box.width = size_param*2; box.height = size_param; box.weight = 3.4*size_param; strcpy (box.contents, "Unknown"); return box; } Function returns a box_t struct A copy of box is returned to the caller via the run time stack. The local variable box disappears after the return.

31 Returning a struct from a function int main (void) { box_t sample_box; sample_box = new_box(3); display_box (&sample_box); return 0; }

32 Returning a struct from a function

33 Arrays of Structs We can create arrays of struct types just like we do for primitive types. box_t sample_box[5]; An array of five structs of type box_t

34 Arrays of Structs int main () { box_t sample_box[5]; int i; for (i = 0; i < 5; i++) { sample_box[i] = new_box(i); } for (i = 0; i < 5; i++) { printf ("Length of sample_box[%d] is %d\n", i, sample_box[i].length); } return 0; }

35 Arrays of Structs

36 Structs within Structs A struct can have another struct as a member typedef struct { int x; int y; } point_t; typedef struct { point_t upper_left; point_t lower_right; } rectangle_t;

37 Accessing Members of Structs within Structs /* This function determines whether a point is inside a rectangle. It counts being on the border as inside. */ int is_inside (point_t* pPoint, rectangle_t* pRect) { return ((pPoint->x >= pRect->upper_left.x ) && (pPoint->x lower_right.x) && (pPoint->y >= pRect->upper_left.y ) && (pPoint->y lower_right.y) ); }

38 Returning a struct to the caller Get coordinates of a point from the user and return the point to the caller. point_t get_point(char* prompt) { point_t pt; printf (prompt); printf ("X: "); scanf ("%d", &pt.x); printf ("Y: "); scanf ("%d", &pt.y); return pt; }

39 Returning a struct to the caller rectangle_t get_rect(char* prompt) { rectangle_t rect; printf (prompt); rect.upper_left = get_point("Upper left corner: \n"); rect.lower_right = get_point("Lower right corner: \n"); return rect; }

40 Summary The “struct” feature in C permits us to define data structures. Any previously defined type can be a member Including other structs Acts as user defined type Use the “dot” notation to access members of a struct using the name of a struct variable. Use the “arrow” notation to access members of a struct using a pointer to the struct.

41 Summary The assignment operator works for structs: box2 = box1; But the comparison operator does not. Can’t say if (box2 == box1)...

42 Summary Functions can have structs as paramters and can return a struct to the caller. Structs are passed by value. Like single variables, not like arrays. Function gets a copy of a struct passed as argument. Call gets a copy of a struct returned as a function value.