struct Properties C struct Types

Similar documents
The assignment requires solving a matrix access problem using only pointers to access the array elements, and introduces the use of struct data types.

Both parts center on the concept of a "mesa", and make use of the following data type:

Motivation was to facilitate development of systems software, especially OS development.

Motivation was to facilitate development of systems software, especially OS development.

struct _Rational { int64_t Top; // numerator int64_t Bottom; // denominator }; typedef struct _Rational Rational;

Pointers, Dynamic Data, and Reference Types

[0569] p 0318 garbage

gcc o driver std=c99 -Wall driver.c bigmesa.c

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

Creating a C++ Program

Homework #3 CS2255 Fall 2012

SYSC 2006 C Winter 2012

A Capacity: 10 Usage: 4 Data:

Memory and Addresses. Pointers in C. Memory is just a sequence of byte-sized storage devices.

BBM 201 DATA STRUCTURES

CSCI 171 Chapter Outlines

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

6.096 Introduction to C++ January (IAP) 2009

CS201 Some Important Definitions

Review of the C Programming Language for Principles of Operating Systems

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

by Pearson Education, Inc. All Rights Reserved.

MATVEC: MATRIX-VECTOR COMPUTATION LANGUAGE REFERENCE MANUAL. John C. Murphy jcm2105 Programming Languages and Translators Professor Stephen Edwards

Object-Oriented Programming

Dynamic Allocation in C

Understanding Pointers

Implementing an abstract datatype. Linked lists and queues

EL6483: Brief Overview of C Programming Language

Lectures 5-6: Introduction to C

Submit your answers to these questions to the Curator under Quizzes as HW08 by the posted due date and time. No late submissions will be accepted.

G52CPP C++ Programming Lecture 9

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

Slide Set 6. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above

An Introduction to C++

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

EL2310 Scientific Programming

Dynamic Allocation in C

// Initially NULL, points to the dynamically allocated array of bytes. uint8_t *data;

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

Lectures 5-6: Introduction to C

Low-Level C Programming. Memory map Pointers Arrays Structures

CS 61C: Great Ideas in Computer Architecture Introduction to C

Unit 3. Operators. School of Science and Technology INTRODUCTION

CPSC 427: Object-Oriented Programming

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

Compiler construction 2009

Short Notes of CS201

Kurt Schmidt. October 30, 2018

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

CS201 - Introduction to Programming Glossary By

A First Look At Java. Didactic Module 13 Programming Languages - EEL670 1

Review of the C Programming Language

Data Structure Series

6.S096 Lecture 4 Style and Structure

Advanced Pointer & Data Storage

CS 2604 Homework 1 Greatest Hits of C++ Summer 2000

Unit 2: Accentuate the Negative Name:

Introduction to Programming Using Java (98-388)

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

SOLUTION: Because the fractions have a common denominator, compare the numerators. 5 < 3

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

Intermediate Programming, Spring 2017*

CS 2604 Homework 2 Solution for Greatest Hits of C++ Fall 2000

BASIC ELEMENTS OF A COMPUTER PROGRAM

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

Malloc Lab & Midterm Solutions. Recitation 11: Tuesday: 11/08/2016

Quick Reference Guide

Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172. In compensation, no class on Friday, Jan. 31.

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Procedural programming with C

In Java we have the keyword null, which is the value of an uninitialized reference type

CSE 143. Linked Lists. Linked Lists. Manipulating Nodes (1) Creating Nodes. Manipulating Nodes (3) Manipulating Nodes (2) CSE 143 1

Creating a String Data Type in C

Full file at C How to Program, 6/e Multiple Choice Test Bank

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

Lesson 1: Arithmetic Review

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

C PROGRAMMING LANGUAGE. POINTERS, ARRAYS, OPERATORS AND LOOP. CAAM 519, CHAPTER5

Arrays, Pointers and Memory Management

Week 9 Part 1. Kyle Dewey. Tuesday, August 28, 12

CA31-1K DIS. Pointers. TA: You Lu

Coding Standards for C

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Coding Standards for C

CMPE-013/L. Introduction to C Programming

Programming, numerics and optimization

Topic 6: A Quick Intro To C

The combination of pointers, structs, and dynamic memory allocation allow for creation of data structures

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

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

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

Object Oriented Software Design II

Binary Tree Node Relationships. Binary Trees. Quick Application: Expression Trees. Traversals

Binary Trees. For example: Jargon: General Binary Trees. root node. level: internal node. edge. leaf node. Data Structures & File Management

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

Classes. Christian Schumacher, Info1 D-MAVT 2013

What have we learned about when we learned about function parameters? 1-1

Transcription:

struct Properties 1 The C struct mechanism is vaguely similar to the Java/C++ class mechanisms: - supports the creation of user-defined data types - struct types encapsulate data members struct Location { int X, Y; ; But there are vital differences: - struct data members are "public", in fact there is no notion of access control - struct types cannot have function members - there is no concept of inheritance or of polymorphism

A struct Example 2 struct Location { int X, Y; ; // declare type globally int main() { struct Location A; A.X = 5; A.Y = 6; struct Location B; B = A; return 0; // declare variable of type Location // set its data members // declare another Location variable // copy members of A into B Note: - assignment is supported for struct types - type declaration syntax used here requires specific use of struct in instance declarations

Another struct Example 3 struct _Location { int X, Y; ; // declare type globally typedef struct _Location Location; // alias a type name int main() { Location A; A.X = 5; A.Y = 6; Location B; B = A; return 0; // declare variable of type Location // set its data members // declare another Location variable // copy members of A into B Note: - use of typedef creates an alias for the struct type - simplifies declaration of instances

struct Limitations What else is supported naturally for struct types? Not much 4 - no automatic support for equality comparisons (or other relational comparisons) - no automatic support for I/O of struct variables - no automatic support for deep copy - no automatic support for arithmetic operations, even if they make sense - can pass struct variables as parameters (default is pass-by-copy of course) - can return a struct variable from a function - can implement other operations via user-defined (non-member) functions

A struct Function Example 5 struct _Location { int X, Y; ; // declare type globally typedef struct _Location Location; // alias a type name void initlocation(location* L, int x, int y) { Note: (*L).X = x; // alternative: L->X = x; (*L).Y = y; Location A; - must pass Location object by pointer so function can modify original copy - given a pointer to a struct variable, we access its members by dereferencing the pointer (to get its target) and then using the member selector operator '.' - the parentheses around the *L are necessary because * has lower precedence than. - however, we can write L->X instead of (*L).X. - use of address-of '&' operator in call to create pointer to A // call: initlocation(&a, 5, 6);

Another struct Function Example 6 struct _Location { int X, Y; ; // declare type globally typedef struct _Location Location; // alias a type name Location updatelocation(location Old, Location Move) { Location Updated; Updated.X = Old.X + Move.X; Updated.Y = Old.Y + Move.Y; return Updated; // make a local Location object // compute its members // return copy of local object; Note: - we do not allocate Updated dynamically (via malloc); there is no need since we know at compile time how many we need (1) and we can just return a copy and avoid the cost of a dynamic allocation at runtime - in C, dynamic allocation should only be used when logically necessary

Typical struct Code Organization 7 // header file Location.h contains declaration of type and // supporting functions #ifndef LOCATION_H #define LOCATION_H struct _Location { int X, Y; ; // declare type globally typedef struct _Location Location; // alias a clean type name Location updatelocation(location Old, Location Move);... #endif // Source file Location.c contains implementations of supporting // functions #include "Location.h" Location updatelocation(location Old, Location Move) {......

More Complex struct Types 8 // A struct type may contain array members, members of other // struct types, anything in fact: #ifndef QUADRILATERAL_H #define QUADRILATERAL_H #include "Location.h" #define NUMCORNERS 4 struct _Quadrilateral { Location Corners[NUMCORNERS]; ; typedef struct _Quadrilateral Quadrilateral;... #endif Note: - even though you cannot assign one array to another and you cannot return an array from a function, you can do both of those things with a struct variable that contains an array member - Why?

Example: Rational Numbers 9 One shortcoming in C is the lack of a type to represent rational numbers. A rational number is the ratio of two integers, where the denominator is not allowed to be zero. Rational numbers are important because we cannot represent many such fractions exactly in decimal form (e.g., 1/3). The struct mechanism in C allows us to implement a type that accurately represents rational numbers (within the restrictions imposed by the limited range of integer types). The following slides are a case study based on a course project.

Designing Data Representation 10 One fact is clear enough: a rational value consists of two integer values. The obvious C approach would be: struct _Rational { int32_t Top; int32_t Bottom; ; typedef struct _Rational Rational; A forward-looking approach might use int64_t instead, buying increased range and doubling the storage cost. Another thought would be to normalize the representation by using a uint32_t for the denominator, so that a negative rational would always use a negative numerator. For this example, we'll stick with the C code shown above.

Designing Operations 11 When implementing a data type, we must consider what operations would be expected or useful to potential users. In this case, we have mathematics as a guide: - creating a Rational object with any valid value - adding two Rational objects to yield a third Rational object - subtracting two Rational objects to yield a third Rational object - multiplying two Rational objects to yield a third Rational object - dividing two Rational objects to yield a third Rational object - taking the absolute value of a Rational object, yielding a second Rational object - negating a Rational object, yielding a second Rational object - comparing two Rational objects, with equals, less-than, etc. - taking the floor/ceiling of a Rational object, yielding an integer

A Specific Operation 12 /** * Compute the sum of Left and Right. * Pre: * *Left and *Right have been properly initialized. * Returns: * A pointer to a Rational object equal to *Left + *Right. */ Rational* Rational_Add(const Rational* Left, const Rational* Right) { Rational *Sum = malloc(sizeof(rational)); Sum->Top = Left->Top * Right->Bottom + Left->Bottom * Right->Top; Sum->Bottom = Left->Bottom * Right->Bottom; Rational_Normalize(Sum); return Sum; Rational First, Second;... // initialize First and Second Rational *Sum = Rational_Add(&First, &Second);

A Different Take on That 13 /** * Compute the sum of Left and Right. * Pre: * *psum is a Rational object * Left and Right have been properly initialized. * Post: * *psum is a normalized representation of Left + Right. */ void Rational_Add(Rational* const psum, const Rational Left, const Rational Right) { psum->top = Left.Top * Right.Bottom + Left.Bottom * Right.Top; psum->bottom = Left.Bottom * Right.Bottom; Rational_Normalize(pSum); Rational First, Second, Sum;... // initialize First and Second Rational_Add(&Sum, First, Second);

An Array Type 14 One way to address (some of) the shortcomings in C arrays would be to implement: struct _iarray { int32_t* Data; uint32_t Dimension; uint32_t Usage; ; typedef struct _iarray iarray; bool iarray_init(iarray* const pa, uint32_t Size) { if ( pa == NULL ) return false; pa->data = calloc(size * sizeof(int32_t)); if ( pa->data == NULL ) { pa->dimension = pa->usage = 0; return false; pa->dimension = Size; pa->usage = 0; return true;

Safe Array Insertion 15 Mutator operations could now be implemented safely: bool iarray_append(iarray* const pa, int32_t Elem) { if ( pa == NULL pa->dimension == pa->usage) { return false; pa->data[usage] = Elem; pa->usage++; return true; Reject insertion if array is full Data[usage] is the first unused cell in the array

Or 16 bool iarray_append(iarray* const pa, int32_t Elem) { if ( pa == NULL ) return false; if ( pa->dimension == pa->usage) { Check whether array is full int32_t *temp = realloc(pa->data, 2 * pa->dimension); if ( pa->data == NULL ) { return false; pa->data = temp; pa->dimension = 2 * pa->dimension; pa->data[usage] = Elem; pa->usage++; return true; realloc() will: Allocate new array or simply "grow" the old one Copy data from old array to new array, if necessary Deallocate old array, if necessary Return NULL if fails