Structures. Basics of Structures (6.1) EECS l Now struct point is a valid type. l Defining struct variables: struct point { int x; int y; };

Similar documents
Contents. Custom data type struct data type Fixed length memory Alias data type

Structures. Chapter 6

BBM#101# #Introduc/on#to# Programming#I# Fall$2013,$Lecture$12$

CS1100 Introduction to Programming

Systems Programming. 05. Structures & Trees. Alexander Holupirek

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Outline. Briefly review the last class Pointers and Structs Memory allocation Linked lists

Character Strings. String-copy Example

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

Advanced Pointer Topics

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #49. Structures in C -1

STRUCTURES & FILE IO

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems

Lecture 2. Xiaoguang Wang. January 16th, 2014 STAT 598W. (STAT 598W) Lecture 2 1 / 41

Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables.

CS 61c: Great Ideas in Computer Architecture

C PROGRAMMING Lecture 4. 1st semester

Lecture 02 C FUNDAMENTALS

Pointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays

These problems are provided to you as a guide for practice. The questions cover important concepts covered in class.

EM108 Software Development for Engineers

Fundamental of Programming (C)

Data and File Structures Laboratory

Procedural programming with C

C Programming Language: C ADTs, 2d Dynamic Allocation. Math 230 Assembly Language Programming (Computer Organization) Thursday Jan 31, 2008

Intermediate Programming, Spring 2017*

The University of Calgary. ENCM 339 Programming Fundamentals Fall 2016

Arrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size]

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

CS 237 Meeting 18 10/22/12

Content. In this chapter, you will learn:

Variables in C. Variables in C. What Are Variables in C? CMSC 104, Fall 2012 John Y. Park

Principles of C and Memory Management

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

Midterm Examination # 2 Wednesday, March 18, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER:

BLM2031 Structured Programming. Zeyneb KURT

Arrays and Pointers (part 1)

High Performance Programming Programming in C part 1

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

Kurt Schmidt. October 30, 2018

IV Unit Second Part STRUCTURES

Linked-List Basic Examples. A linked-list is Linear collection of self-referential class objects, called nodes Connected by pointer links

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Midterm Examination # 2 Wednesday, March 19, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER:

C Programming Multiple. Choice

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

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

Arrays, Pointers and Memory Management

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

Read: Kernighan & Ritchie

Computer Organization & Systems Exam I Example Questions

BSM540 Basics of C Language

Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

CSCI 171 Chapter Outlines

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Chapter 1 & 2 Introduction to C Language

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam

CS61C : Machine Structures

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

CS 261 Data Structures. Introduction to C Programming

The C Programming Language Part 4. (with material from Dr. Bin Ren, William & Mary Computer Science, and

Fundamental of Programming (C)

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

Structures. CSE 142 Programming I. Chapter 11. Review: Data Structures. Defining structs. Terminology. Structs: Heterogeneous Structures

Basic and Practice in Programming Lab7

CSE2301. Dynamic memory Allocation. malloc() Dynamic Memory Allocation and Structs

ET156 Introduction to C Programming

A Fast Review of C Essentials Part I

Fundamentals of Programming

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

Pointers. Introduction

CS61C Machine Structures. Lecture 4 C Structs & Memory Management. 9/5/2007 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

More about BOOLEAN issues

Linked Lists. .. and other linked structures. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

!"#$% &'($) *+!$ 0!'" 0+'&"$.&0-2$ 10.+3&2),&/3+, %&&/3+, C,-"!.&/+"*0.&('1 :2 %*10% *%7)/ 30'&. 0% /4%./

Structures. What is a structure? It is a collection of possibly different types Name the collection Name the components

JTSK Programming in C II C-Lab II. Lecture 3 & 4

CS3157: Advanced Programming. Announcement

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

mith College Computer Science CSC270 Spring 2016 Circuits and Systems Lecture Notes, Week 11 Dominique Thiébaut

Data types, variables, constants

Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah. Lecturer Department of Computer Science & IT University of Balochistan

MPATE-GE 2618: C Programming for Music Technology. Unit 5.1

Arrays and Pointers (part 1)

CS 237 Meeting 19 10/24/12

Linked Data Representations

C: How to Program. Week /Mar/05

Data Type. structure. C Programming Lecture 11 : Structuret. struct union. typedef. A collection of one or more variables

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

Principles of C and Memory Management

CS240: Programming in C

CS 61C: Great Ideas in Computer Architecture C Pointers. Instructors: Vladimir Stojanovic & Nicholas Weaver

Mechatronics and Microcontrollers. Szilárd Aradi PhD Refresh of C

Pointers and Arrays 1

Transcription:

Structures EECS 2031 25 September 2017 1 Basics of Structures (6.1) struct point { int x; int y; keyword struct introduces a structure declaration. point: structure tag x, y: members The same member names may occur in different structures. l Now struct point is a valid type. l Defining struct variables: struct point pt; struct point maxpt = {320, 200 l A struct declaration defines a type. struct {... } a, b, c; or struct point a,b,c; is syntactically analogous to int a, b, c; 2 1

Using Structures l Members are accessed using operator. structure-name.member struct point pt; printf( %d,%d", pt.x, pt.y); double sqrt(double); /* function prototype */ double dist = sqrt((double)pt.x * pt.x + (double)pt.y * pt.y); 3 Structure Name Space l Structure and members names have their own name space separate from variables and functions. struct point point; struct point { int x; int y; } x; /* Both are valid but not recommended. */ 4 2

Nested Structures struct rectng { struct point pt1; struct point pt2; struct rectng screen; screen.pt1.x = 1; screen.pt1.y = 2; screen.pt2.x = 8; screen.pt2.y = 7; 5 Structures and Functions (6.2) l Returning a structure from a function. /* makepoint: make a point from x and y components */ struct point makepoint( int x, int y ) { struct point temp; temp.x = x; temp.y = y; return temp; } struct rectng screen; struct point middle; struct point makepoint( int, int ); screen.pt1 = makepoint( 0, 0 ); screen.pt2 = makepoint( XMAX, YMAX ); middle = makepoint( (screen.pt1.x + screen.pt2.x)/2, (screen.pt1.y + screen.pt2.y)/2 ); 6 3

Structures and Functions (cont.) l Passing structure arguments to functions: structure parameters are passed by values like int, char, float, etc. A copy of the structure is sent to the function. /* addpoints: add two points */ struct point addpoint( struct point p1, struct point p2 ) { p1.x += p2.x; p1.y += p2.y; return p1; } l Note: the components in p1 are incremented rather than using an explicit temporary variable to emphasize that structure parameters are passed by value like any others (no changes to original struct). 7 Pointers to Structures l If a large structure is to be passed to a function, it is generally more efficient to pass a pointer than to copy the whole structure. struct point *pp; struct point origin = makepoint( 0, 0 ); pp = &origin; printf("origin is (%d,%d)\n", (*pp).x, (*pp).y); l Note: *pp.x means *(pp.x), which is illegal (why?) 8 4

Precedence and Associativity 9 Pointers to Structures: Example /* addpoints: add two points */ struct point addpoint (struct point *p1, struct point *p2) { struct point temp; temp.x = (*p1).x + (*p2).x; temp.y = (*p1).y + (*p2).y; return temp; } main() { struct point a, b, c; /* Input or initialize structures a and b */ c = addpoint( &a, &b ); } 10 5

Pointers to Structures: Shorthand l (*pp).x can be written as pp->x printf("origin is (%d,%d)\n", pp->x, pp->y); struct rect r, *rp = &r; r.pt1.x = 1; rp->pt1.x = 2; (r.pt1).x = 3; (rp->pt1).x = 4; l Note: Both. and -> associate from left to right. 11 malloc() pointer = (type *) malloc (no_of_elements * sizeof (element)) double *pd; pd = (double *) malloc(sizeof(double)); int *pi; pi = (int *) malloc(sizeof(int)); free ( pi ); pi = (int *) malloc(10 * sizeof(int)); char *str; str = (char *) malloc(maxsize * sizeof(char)); 12 6

Arrays of Structures (6.3) struct dimension { float width; float height; struct dimension chairs[12]; struct dimension *tables; tables = (struct dimension *) malloc (20 * sizeoff(struct dimension)); 13 Initializing Structures struct dimension sofa = {2.0, 3.0 struct dimension chairs[] = { {1.4, 2.0}, {0.3, 1.0}, {2.3, 2.0} 14 7

Arrays of Structures: Example struct key { char *word; int count; struct key keytab[nkeys]; struct key *p; for (p = keytab; p < keytab + NKEYS; p++) printf("%4d %s\n", p->count, p->word); struct key { char *word; int count; } keytab[] = { "auto", 0, "break", 0, "case", 0, "char", 0, "const", 0, "continue", 0, "default", 0, /*... */ "unsigned", 0, "void", 0, "volatile", 0, "while", 0 15 Pointers to Structures (6.4) struct key keytab[nkeys]; struct key *p; for (p = keytab; p < keytab + NKEYS; p++) printf("%4d %s\n", p->count, p->word); l p++ increments p by the correct amount (i.e., structure size) to get the next element of the array of structures. struct { char c; /* one byte */ int i; /* four bytes */ l What is the total structure size? l Use the sizeof operator to get the correct structure size. 16 8

Self-referential Structures (6.5) Example: (singly) linked list struct list { int data; struct list *next; 3 17 Linked List l Pointer head points to the first element l Last element pointer is NULL l Example (next slide): build a linked list with data being non-negative integers, then search for a number. Insertion at the end (rear) of the list. l We also learn how to dynamically allocate a structure. head -1 10 6 NULL 18 9

Linked List Implementation #include <stdio.h> #include <stdlib.h> main() { struct list { int data; struct list *next; } *head, *p, *last; int i; /* Create a dummy node, which simplifies insertion and deletion */ head = (struct list *) malloc ( sizeof( struct list ) ); head >data = -1; head >next = NULL; last = head; scanf( %d, &i ); /* input 1 st element */ while( i >= 0 ) { p = (struct list *) malloc( sizeof( struct list ) ); p >data = i; p >next = NULL; last >next = p; last = p; scanf( %d, &i ); } /* while */ printf( Enter the number to search for ); scanf( %d, &i ); for( p = head; p!= NULL; p = p >next ) if( p >data == i ) printf( "FOUND %d \n, i ); } /* main */ 19 Pointers to Structures: More Examples l The operators. and -> along with ( ) and [ ] have the highest precedence and thus bind very tightly. 20 10

Example 1 ++p->len (++p)->len (p++)->len ó ++(p->len) ó p++->len 21 Example 2 22 11

typedef (6.7) l For creating new data type names typedef int Length; Length len, maxlen; Length *lengths[]; typedef char *String; String p, lineptr[maxlines]; p = (String) malloc(100); int strcmp(string, String); 23 typedef with struct l We can define a new type and use it later typedef struct { int x,y; float z; } mynewtype; mynewtype a, b, c, x; l Now, mynewtype is a type in C just like int or float. 24 12

Self-referential Structures: More Examples l Binary trees (6.5) l Hash tables (6.6) To be covered later if time permits. 25 Reminders l Lab test 1 (Oct. 20 and 23) l Midterm (Oct. 30) l Next lecture: Pointers (part 2) 26 13