C++ Structures Programming Workshop 2 (CSCI 1061U)

Similar documents
Classes and Data Abstraction: struct

C++ For Science and Engineering Lecture 15

Text File I/O. #include <iostream> #include <fstream> using namespace std; int main() {

Homework Assignment #2 (revised)

VARIABLES & ASSIGNMENTS

Prof. Carl Schultheiss MS, PE. CLASS NOTES Lecture 12

Laboratory 7. Programming Workshop 2 (CSCI 1061U) Faisal Qureshi.

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

What we will learn about this week: Declaring and referencing arrays. arrays as function arguments. Arrays

pointers + memory double x; string a; int x; main overhead int y; main overhead

CS Introduction to Programming Midterm Exam #2 - Prof. Reed Fall 2015

The C++ Language. Arizona State University 1

Data Representation and Storage

Chapter 2. Procedural Programming

C++ Quick Guide. Advertisements

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

Input/output. Remember std::ostream? std::istream std::ostream. std::ostream cin std::istream. namespace std { class ostream { /*...

Advanced I/O Concepts

This chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files.

Data Representation and Storage. Some definitions (in C)

Complex data types Structures Defined types Structures and functions Structures and pointers (Very) brief introduction to the STL

Pointers II. Class 31

6.096 Introduction to C++ January (IAP) 2009

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

cout << "How many numbers would you like to type? "; cin >> memsize; p = new int[memsize];

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Introduction Of Classes ( OOPS )

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

Exceptions, Case Study-Exception handling in C++.

BITG 1233: Introduction to C++

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 11: Records (structs)

LECTURE 02 INTRODUCTION TO C++

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1

Inheritance, and Polymorphism.

CS24 Week 3 Lecture 1

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

UEE1303(1070) S 12 Object-Oriented Programming in C++

Week 3 Lecture 2. Types Constants and Variables

Week 3: File I/O and Formatting 3.7 Formatting Output

Convenient way to deal large quantities of data. Store data permanently (until file is deleted).

Stack memory - "scratch pad" memory that is used by automatic variables.

Random File Access. 1. Random File Access

Exercise 1.1 Hello world

Integer Data Types. Data Type. Data Types. int, short int, long int

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 7. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University

Chapter-14 STRUCTURES

2. It is possible for a structure variable to be a member of another structure variable.

Function Overloading

Scientific Computing

Chapter 1: Object-Oriented Programming Using C++

BEng (Hons) Electronic Engineering. Resit Examinations for / Semester 1

Programming. C++ Basics

C++ Programming Lecture 10 File Processing

C++ Binary File I/O. C++ file input and output are typically achieved by using an object of one of the following classes:

Jordan University of Science & Technology Department of Computer Science CS 211 Exam #1 (23/10/2010) -- Form A

Bit Manipulation in C

First of all, it is a variable, just like other variables you studied

CS 31 Discussion 1A, Week 8. Zengwen Yuan (zyuan [at] cs.ucla.edu) Humanities A65, Friday 10:00 11:50 a.m.

Lecture on pointers, references, and arrays and vectors

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

Structs. Comp Sci 1570 Introduction to C++ Introduction. Aggregate data. Example. General syntax Object initialization Initialization and access

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

CS2141 Software Development using C/C++ C++ Basics

Lecture 2 More C++ Jon Macey

Fast Introduction to Object Oriented Programming and C++

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

Dynamic Data Structures. CSCI 112: Programming in C

Object Oriented Design

Lab 8 The Stack (LIFO) Structure

Exception with arguments

Input And Output of C++

Object Reference and Memory Allocation. Questions:

CPSC 427: Object-Oriented Programming

CHAPTER 3 BASIC INSTRUCTION OF C++

Memory and Pointers written by Cathy Saxton

A First Program - Greeting.cpp

CS 376b Computer Vision

COMP322 - Introduction to C++

Tema 6: Dynamic memory

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

CS31 Discussion. Jie(Jay) Wang Week8 Nov.18

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Polymorphism CSCI 201 Principles of Software Development

Fundamentals of Programming Session 24

C++ 프로그래밍실습. Visual Studio Smart Computing Laboratory

Number Systems. Binary Numbers. Appendix. Decimal notation represents numbers as powers of 10, for example

Introduction to Programming

I/O Streams and Standard I/O Devices (cont d.)

Functions, Arrays & Structs

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

QUIZ. What are 3 differences between C and C++ const variables?

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Programming II Lecture 2 Structures and Classes

Transcription:

C++ Structures Programming Workshop 2 (CSCI 1061U) Faisal Qureshi http://faculty.uoit.ca/qureshi University of Ontario Institute of Technology C++ struct struct keyword can be used to define new data types in C++. Defining a struct The following code defines a Rect data type that can be used to store the height and the width of a rectangle. struct Rect We can also do the following typedef struct Rect; This tells the compiler that we are defining a struct named Rect. This struct contains 2 variables inside of it: an int named h and an int named w. These variables that are part of the struct are called members (or fields). Currently no memory is allocated for this struct. This simply tells the compiler how the struct Rect looks like. Declaring variables To use this struct, we can declare a variable of type Rect Above statement declares a variable of type Rect. It allocates the memory necessary to hold struct contents. It is possible to see how much memory a struct takes by using the sizeof() function. E.g., sizeof(rect) will return the size (in bytes) of this struct. Accessing members We use the. (dot) operator to access the members as follows 1

The above lines set the height and the width of r1 equal to 23 and 90, respectively. As with normal variables, struct member variables are not initialized, and will typically contain junk. We must initialize them manually. Assignment Assignment works as expected. Rect r2 = r1; r2 is a copy of r1, i.e., it too represents a rectangle of height 23 and width 90. Reading and writing to binary files The following code writes and read struct from a file. ofstream f("tmp.dat", ios::binary); f.write((char*) &r1, sizeof(rect)); and for reading ifstream f("tmp.dat", ios::binary); f.read((char*) r1, sizeof(rect)); The following, however, won t work. ofstream f("tmp.txt"); f << r1; or ifstream f("tmp.txt"); f >> r; This is because struct is a user-defined type. And currently operators >> and << are not defined for it. Pointers to struct Similar to regular variables, it is possible to declare a pointer to a struct variable. 2

... Rect* pr; pr = &r; Notice that we use & to get the address of the struct variable (similar to other variables). Accessing members when using struct pointers Use the -> operator to access the members as follows: Rect* pr; pr = &r; pr->h = 3; pr->w = 34; Now the variable r represents a rectangle with height 3 and width 34. Initializing struct Lets consider the following struct that represents an Employee struct Employee long id; short age; It is possible to define and initialize a variable of type Employee in one go as follows: Employee e = 1033242, 34, 100000.34 cout << e.id << endl; // prints 1033242 cout << e.age << endl; // prints 34 cout << e.wage << endl; // prints 100000.34 Using struct with functions It is possible to pass the entire struct to a function. #include <iostream> using namespace std; struct Rect int area(rect r) return r.h * r.w; int main() 3

Rect r = 5, 23 cout << "Area of rectangle = " << area(r) << endl; return 0; **It is also possible to return a struct from a function.* This is one of the few ways to return multiple values from a function. #include <iostream> using namespace std; struct Employee long id; short age; Employee make_ceo(int id, int age) Employee e; e.id = id; e.age = age; e.wage = 10000.0; return e; int main() Employee e = make_ceo(1, 24); return 0; Nest struct struct can contain other struct struct Employee short id; int age; struct Company Employee CEO; // Employee is a struct within the Company struct int numberofemployees; Company c; Use the. (dot) operator to get to the members c.ceo.age = 25; 4

This sets the age of the CEO of company c equal to 25. Struct alignment Typically, the size of a struct is the sum of the size of all its members, but not always! The size of the struct below is 8 as expected: (2*sizeof(int)). struct Rect The size of the struct below on my machine is 12, which is odd since char only takes 1 byte. struct Rect char a; In general, the size of a struct is at least as large as the size of all the variables it contains. But it could be larger. For performance reasons, the compiler will sometimes add gaps into structures (this is called padding). 5