Structures, Unions, Enumerations

Slides:



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

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.
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.
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.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
C structures and unions (Reek, Ch. 10) 1CS 3090: Safety Critical Programming in C.
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
Data Type. A data type defines a set of values that a variable can store along with a set of operations that can be performed on that variable. Common.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 23P. 1Winter Quarter Structs and Enumeration.
C Tokens Identifiers Keywords Constants Operators Special symbols.
Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 23P. 1Winter Quarter Structs and Enumeration Lecture 23.
16. STRUCTURES, UNIONS, AND ENUMERATIONS. Declaring Structures A structure is a collection of one or more components (members), which may be of different.
Array, Structure and Union
Today’s Material Aggregate Data Types: Structures and Unions
Engineering Problem Solving with C Fundamental Concepts Chapter 7 Structures.
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.
 Structures are like arrays except that they allow many variables of different types grouped together under the same name. For example you can create.
Chapter 13: Structures. In this chapter you will learn about: – Single structures – Arrays of structures – Structures as function arguments – Linked lists.
ECE 103 Engineering Programming Chapter 50 Structures Unions, Part 2 Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE.
© Oxford University Press All rights reserved. CHAPTER 8 STRUCTURES.
+ Structures and Unions. + Introduction We have seen that arrays can be used to represent a group of data items that belong to the same type, such as.
Weekly C-minar Week 0. Today: Steps of the compile Basic inclusion/syntax rules Low-cost containment Debugging.
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.
1 Lecture10: Structures, Unions and Enumerations 11/26/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Structure A collection of values (members) struct date{ int day; char month[10]; int year; }; Declare a structure variable struct date today; struct struct_name.
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.
Pointers. Addresses in Memory Everything in memory has an address. C allows us to obtain the address that a variable is stored at. scanf() is an example.
Java Programming Language Lecture27- An Introduction.
C LANGUAGE UNIT 3. UNIT 3 Arrays Arrays – The concept of array – Defining arrays – Initializing arrays.
Parameter Passing: Arrays 1.Create new variables (boxes) for each of the formal parameters allocated on a fresh stack created for this function call. int.
Ex-1 #include <stdio.h> struct sample { int a=0; char b='A';
User-Written Functions
Chapter 8 Arrays, Strings and Pointers
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
CSE 220 – C Programming Pointers.
Functions and Pointers
Chapter 10-1: Structure.
TMF1414 Introduction to Programming
Visit for more Learning Resources
Module 2 Arrays and strings – example programs.
CSE101-Lec#3 Components of C Identifiers and Keywords Data types.
Pointers.
Functions and Pointers
DATA HANDLING.
Buy book Online -
Lecture 9 Structure 1. Concepts of structure Pointers of structures
Structures Lesson xx In this module, we’ll introduce you to structures.
Programming in C #4 Structs and Unions.
C Structures, Unions, Bit Manipulations and Enumerations
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Derived types.
CS111 Computer Programming
Programming in C Pointer Basics.
Windows Programming Lecture 04
Unions A union is a custom data type used for storing several variables in the same memory space. Although you can access any of those variables at any.
Programming in C Pointer Basics.
C Structures, Unions, Bit Manipulations and Enumerations
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Java Programming Language
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Chapter 9: Pointers and String
Engineering H192 Winter 2005 Structs and Enumeration Prof. Almas Ansari Dept of Computer Science Engineering Anjuman College of Engineering & Technology..
Programming in C Pointer Basics.
C Language B. DHIVYA 17PCA140 II MCA.
CSCE 206 Lab Structured Programming in C
Pointers, Dynamic Data, and Reference Types
Structures, Unions, and Enumerations
Presentation transcript:

Structures, Unions, Enumerations CSE 220 – C Programming Structures, Unions, Enumerations

Custom Data Types: Structures Union (optional content) Enumeration (optional content)

Structure Variables Structure: a collection of values Members may have different types Members have names: To select a member, specify name not position Use when we need to store a collection of related data items

Examples char make[30]; char model[10]; float engineSize; Consider a program that needs to store the following information about a car: Make, model, engine size, horse power What variables do you need to declare? char make[30]; char model[10]; float engineSize; int horsePower;

On HackerRank and the CSE machines, what is the size of a char ? 1 bytes (8 bits) 2 bytes (16 bits) 4 bytes (32 bits) I don't know

On HackerRank and the CSE machines, what is the size of a int ? 1 bytes (8 bits) 2 bytes (16 bits) 4 bytes (32 bits) I don't know

On HackerRank and the CSE machines, what is the size of a float ? 1 bytes (8 bits) 2 bytes (16 bits) 4 bytes (32 bits) I don't know

On HackerRank and the CSE machines, what is the size of a char[10]? 10 bytes (80 bits) 20 bytes (160 bits) 40 bytes (320 bits) I don't know

Examples char make1[30], make2[30], make3[30]; Consider a program that needs to store the following information about a car: Make, model, engine size, horse power What if you need to collect this data about 3 cars? char make1[30], make2[30], make3[30]; char model1[10], model2[10], model3[10]; float engineSize1, engineSize2, engineSize3; int horsepower1, horsepower2, horsepower3;

Example Car make model hp engSz Car char make[30]; char model[10]; Better to have one variable containing all pieces of information: Car make model hp engSz Car char make[30]; char model[10]; float engineSize; int horsePower;

On HackerRank and the CSE machines, what is the size of a struct Car? 48 bytes 56 bytes 60 bytes I don't know Car char make[30]; char model[10]; float engineSize; int horsePower;

Declaration To declare a structure variable, you need to specify the type, the elements and the variable name struct { …. } var; //Single variable: var struct { …. } var1, var2; //Multiple variables: var1, var2 Example: struct { char make[30]; char model[10]; float engineSize; int horsepower; } car1, car2, car3;

Examples Circle float x; float y; float radius; Student Declare a struct to represent the following: struct { float x; float y; float radius; } circle; Circle float x; float y; float radius; struct { char name[100]; int grade; } student; Student char name[100]; int grade;

Storage struct { char make[30]; int year; } car1; make year car1 Members are stored in memory in the order in which they are declared. make year car1

Initialization struct { char make[MAX_LEN +1]; int year; } car1 = {“Volvo”, 2008}, car2 = {“BMW”, 2010}; Variables can be initialized at the same time of declaration Values in initializer must appear in the same order as in the structure

Accessing members To access the value of a struct member use: struct_name.member_name: car1.year = 2008; strcpy(car1.make, “Ford”); printf(“My new car is a %d %s\n”, car2.year, car2.make); car2.year++; scanf(“%d”, &car1.year);

What does this code output? struct { char title[101]; int year; float imdb_rating; } matrix = {"The Matrix", 1999, 8.7}, lotr; strcpy(lotr.title, "Lord of the Rings"); lotr.imdb_rating = 8.8; lotr.year = 2001; char * better_movie; if (lotr.imdb_rating > matrix.imdb_rating) { better_movie = lotr.title; } else { better_movie = matrix.title; } printf("%s", better_movie); The Matrix Lord of the Rings lotr.title I don't know What does this code output?

Copying a struct car1 = car2; Copy a struct into another: copies car2.year into car1.year and car2.make into car1.make car1 and car2 must have compatible types (see next slide). Arrays cannot be copied using the = operator, but when inside a struct, they can. Cannot use == or != to check if 2 structs are equal or not

Compatible Structures char make[M+1]; int year; } car1, car2; … } car3; car1 and car2 are compatible car1 and car3 are not compatible

Structure types Repeating structure information: program hard to maintain The 2 structs are not compatible with each others Solution: define a type for the struct or use tag struct { char make[M+1]; int year; } car1, car2; … } car3;

Structure Tag Car is a tag, a name given to that particular structure You have not yet declared a variable having this structure struct Car { char make[M+1]; int year; }; //Need a ; here … struct Car car1; //Need the keyword struct struct Car car2 = {“Ford”, 2009}; car1 = car2; //Valid, since types are compatible

What does this code output? struct Movie { char title[101]; int year; float imdb_rating; } Movie matrix = {"The Matrix", 1999, 8.7}; Movie lotr = {"Lord of the Rings", 2001, 8.8}; Movie better_movie; if (lotr.imdb_rating > matrix.imdb_rating) { better_movie = lotr; } else { better_movie = matrix; printf("%s", better_movie.title); Lord of the Rings The Better Movie Error I don't know What does this code output?

What does this code output? struct Movie { char title[101]; int year; float imdb_rating; }; struct Movie matrix = {"The Matrix", 1999, 8.7}; struct Movie lotr = {"Lord of the Rings", 2001, 8.8}; struct Movie better_movie; if (lotr.imdb_rating > matrix.imdb_rating) { better_movie = lotr; } else { better_movie = matrix; } printf("%s", better_movie.title); Lord of the Rings The Better Movie Error I don't know What does this code output?

Structure Type Definition (optional content) typedef struct { char make[M+1]; int year; } Car; //Need a ; here … Car car1; /* Don’t need the keyword struct, since struct defined with typedef */ Car car2 = {“Ford”, 2009}; car1 = car2;

Arguments and Return value Structs can be passed as parameters to a function and as return values: void printCarInfo(struct Car car) { printf(“%d: %s\n”, car.year, car.make); } struct Car newerCar(struct Car car1, struct Car car2) { if (car1.year > car2.year) { return car1; return car2; Structs are passed by value (a copy is made and sent to the function)

Pointers to Structs //Define struct type struct Circle { float x; float y; float radius;}; struct Circle c, *ptr; //Declare a circle, and a pointer ptr = &c; //Access using the pointer: (*ptr).x = 2.0; (*ptr).y = 3.0; //Alternative way to access members (optional content): ptr -> x = 2.0; ptr -> y = 3.0;

Nested Structures struct Engine { float size; int horsepower; } ; May declare nested structures: struct Engine { float size; int horsepower; } ; struct Car { char make[M+1]; int year; struct Engine engine; struct Car car1; car1.engine.size = 3.0f; car1.engine.horsepower = 245;

Array of Structs struct Student { char name[M+1]; int grade; } ; Array whose elements are structures: struct Student { char name[M+1]; int grade; } ; struct Student cse_students[50]; struct Student honors_students[ ] = { {“Jim”, 85}, {“Dalia”, 95}, {“Katie”, 85}}; printInfo(&honors_students[1]); //Pass a pointer to the ith element

Array of Structs void printInfo(struct Student *stdPtr) { Define printInfo void printInfo(struct Student *stdPtr) { printf(“Name: %s\tGrade: %d\n”, (*stdPtr).name, (*stdPtr).grade); }

Custom Data Types: Structures Union (optional content) Enumeration (optional content)

Unions (optional content) Consist of one or more members, possibly of different types. All members share the same space Store one member at a time Allocates enough space to fit the largest union { char ch; int i; } u; ch i u

Example (optional content) Use to build mixed data structures struct Truck { char make[30]; int year; float bedLength; int towCap; }; struct Car { char make[30]; int year; int seats; }; struct Vehicle { char type; union { struct Truck truck; struct Car car; } details; };

Enumerations (optional content) Enumerated type: type whose values are listed enum {red, yellow, green, blue, black, orange} c1, c2; Enumeration Tag: enum Color {red, yellow, green, blue, black, orange}; enum Color c1, c2; //Declare 2 variables of type Color Enumeration typedef: typedef enum {PASS, FAIL} Grade; Grade g1, g2; //Declare 2 variables of type Grade

Use as integers (optional content) Enum variables are stored as integers: enum {red, yellow, green} c1; enum {red = 0, yellow = 1, green= 2} c2; enum {car = 10, truck = 20, suv = 30, bus} vt; c1 = green; //c1 = 2 vt = truck; //vt = 20 int val = vt + 5; //val = 25 int y = bus; //y = 31