1 6.1 Basics of Structures 6.2 Structures and Functions 6.3 Arrays of Structures 6.4 Pointers to Structures 6.5 Self-referential Structures + Linked List.

Slides:



Advertisements
Similar presentations
Chapter 10 C Structures, Unions, Bit Manipulations and Enumerations Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc.
Advertisements

C Structures What is a structure? A structure is a collection of related variables. It may contain variables of many different data types---in contrast.
C Programming Lecture 23 Enumeration Types Structures.
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.
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 A structure is a collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling.
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
1 6.1 Basics of Structures 6.2 Structures and Functions 6.3 Arrays of Structures 6.4 Pointers to Structures 6.5 Self-referential Structures + malloc +
Structures, Unions, and Typedefs CIS 1057 Fall Structures, Unions, and Typedefs CIS 1057 Computer Programming in C Fall 2013 (Many slides based on/borrowed.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 7 : September 8.
Kernighan/Ritchie: Kelley/Pohl:
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
Structures, Unions, and Typedefs CS-2301 D-term Structures, Unions, and Typedefs CS-2301 System Programming D-term 2009 (Slides include materials.
C and Data Structures Baojian Hua
C structures and unions (Reek, Ch. 10) 1CS 3090: Safety Critical Programming in C.
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
Structures and UnionsCS-2301 B-term Structures and Unions CS-2301, System Programming for Non-majors (Slides include materials from The C Programming.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Structures, Unions, and Typedefs CS-2303, C-Term Structures, Unions, and Typedefs CS-2303 System Programming Concepts (Slides include materials from.
1 Structures. 2 C gives you several ways to create a custom data type. –The structure, which is a grouping of variables under one name and is called an.
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.
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.
1 Homework HW6 due class 22 K&R 6.6 K&R 5.7 – 5.9 (skipped earlier) Finishing up K&R Chapter 6.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Stack and Heap Memory Stack resident variables include:
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
CS212: Object Oriented Analysis and Design Lecture 10: Copy constructor.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
0 Chap. 5 Pointers and Arrays 5.3Pointers and Arrays 5.4Address Arithmetic 5.5Character Pointers and Functions 5.6Pointer Arrays; Pointers to Pointers.
0 4.3 First Large Coding Example: calculator (kr76-79): Example of a Stack Machine Description of the problem and approach Pseudo code Flat implementation.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
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.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Array, Structure and Union
 2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
Homework Finishing up K&R Chapter 6 today Also, K&R 5.7 – 5.9 (skipped earlier)
CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2013 CMPE-013/L Unions and Bitfields Gabriel Hugh Elkaim Spring 2013.
Today’s Material Aggregate Data Types: Structures and Unions
The Cn Language over view The Cn language strongly on ANSI C. So if you are familiar with ANCI it is not so tough to deal with Cn language. Basic Data.
Chapter 13: Structures. In this chapter you will learn about: – Single structures – Arrays of structures – Structures as function arguments – Linked lists.
Structures and Unions in C Alan L. Cox
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.
+ 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.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
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.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 5.
Introduction to Computers and Programming Class 24 Structures (structs) Professor Avi Rosenfeld.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
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.
Structures CSE 2031 Fall March Basics of Structures (6.1) struct point { int x; int y; }; keyword struct introduces a structure declaration.
STRUCTURES. INTRODUCTION A structure is same as that of records. It stores related information about an entity. Structure is basically a user defined.
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)
Lecture 5 Pointers 1. Variable, memory location, address, value
DATA HANDLING.
Lecture 9 Structure 1. Concepts of structure Pointers of structures
C Structures, Unions, Bit Manipulations and Enumerations
CS 240 – Lecture 18 Command-line Arguments, Typedef, Union, Bit Fields, Pointers to Functions.
Structures, Unions, and Typedefs
Structures CSE 2031 Fall February 2019.
Data Structures and Algorithms Introduction to Pointers
Structures CSE 2031 Fall April 2019.
Structures CSE 2031 Fall May 2019.
Structures EECS July 2019.
C Structures and Memory Allocation
Structures, Unions, and Enumerations
Presentation transcript:

1 6.1 Basics of Structures 6.2 Structures and Functions 6.3 Arrays of Structures 6.4 Pointers to Structures 6.5 Self-referential Structures + Linked List (6.6 Table Lookup –– not treated in this course) 6.7 Typedef –– 2 nd visit 6.8 Unions 6.9 Bit-fields Chap. 6 Structures + Linked List System-oriented Programming, B. Hirsbrunner, diuf.unifr.ch/pai/ip, Lecture 7 – 31 March 2015 KR6 + linked list: ~90’; Exercises: ~90’

2 6.1 Basics of Structures: definition and examples Definition A structure is a collection of one or more variables, possibly of different types. Examples of type declarations (no memory allocation) struct {int x; int y}; struct point {int x; int y;}; –‘point' is an optional structure tag Examples of variables definitions (with memory allocation) struct {int x; int y} p; struct point {int x; int y} p1; struct point p2, p3; Examples of variables definitions with initialization struct {int x; int y} p = {5, 5}; struct point {int x; int y} p1 = {0,1}; struct point p2 = {1,2};

3 6.1 Basics of Structures: more definitions and examples Definitions 1.The variables named in a structure are called members. 2.A struct declaration 'struct {…};' defines a type i.e. 'struct {…} x;' is syntactically analogous to 'int x;' More examples of variable declarations/definitions with initialization 1.struct rectangle {struct point p1; struct point p2} r = {{0,1}, {1,2}} ; // nested structures with initialization 1.struct point f(…); // a function returning a value of type 'struct point' 1.{ // local 'struct point' variable definitions with initialization struct point p1 = {0,1}, p2 = f(…); // assuming that f(…) returns a value of type struct point }

4 6.1 Basics of Structures: name overloading Name Overloading Following objects can have the same name without conflicting, since they can always be distinguished by context: -structure tag -structure member variable -ordinary (i.e. non-member) variable Example (overloading should be used very carefully) struct x {int x;}; // declaraton of type 'struct x', with a member x struct x x = {1}; // declaration of variable x of type 'struct x', // with member x initialized to 1 Usage: printf("%d", x.x);

5 6.1 Basics of Structures: structure member operator '.' Definition A member of a particular structure is referred as follows: structure_name.member Examples of expressions with the structure member operator '.' p.x r.pt1.x Memory Diagrams

6 6.2 Structures and Functions Legal Operations -assignment -passing arguments to functions and returning values from functions -taking its address with & -accessing its members with. or –> -initialization by a list of constant member values Parameter Passing to Functions -pass components separately, eventually pass their addresses -pass an entire structure, eventually its address Remark Structure parameter are passed by value like any others

7 6.2 Structures and Functions : example 1 #define min(a, b) ((a) < (b) ? (a) : (b)) #define max(a, b) ((a) > (b) ? (a) : (b)) /* canonrect: canonicalize coordinates of rectangle */ struct rect canonrect(struct rect r) { struct rect temp; temp.p1.x = min(r.p1.x, r.p2.x); temp.p1.y = min(r.p1.y, r.p2.y); temp.p2.x = max(r.p1.x, r.p2.x); temp.p2.y = max(r.p1.y, r.p2.y); return temp; }

8 6.2 Structures and Functions : example 2 struct rect canonrect(struct rect *rp) { struct rect temp; temp.p1.x = min((*rp).p1.x, (*rp).p2.x); temp.p1.y = min((*rp).p1.y, (*rp).p2.y); temp.p2.x = max( rp->p1.x, rp->p2.x); temp.p2.y = max( rp->p1.y, rp->p2.y); return temp; } Remark. Alternative notation for pointer p to a structure: p –> member-of-structure

9 6.2 Structures and Functions :. and –> Both. and -> associate from left to right, so if we have struct rect r, *rp = &r; then these six expressions are equivalent: r.p1.x (r.p1).x (*rp).p1.x ((*rp).p1).x rp->p1.x (rp->p1).x Remark. The structure operators. and ->, together with () for function calls and [] for subscripts, are at the top of the precedence hierarchy and thus bind very tightly.

Arrays of Structures: example + size of struct key { char *word; int count; } keytab[NKEYS] = {{"auto",0},...}; sizeof (unary operator used to calculate the amount of space any data-element / data-types occupies in memory, in number of bytes) : sizeof variable or expression // can also be specified with parentheses () sizeof (type-name) // parentheses () are mandatory -declares a structure type 'struct key', -defines an array 'keytab[NKEYS]' of type 'struct key', and -sets aside storage for this array Example #define NKEYS (sizeof keytab / sizeof(struct key)) or #define NKEYS (sizeof keytab / sizeof keytab[0])

Pointers to Structures 6.5 Self-referential Structures: declarations and definitions struct node_t {int data; struct node_t *next}; struct node_t node = {1, &node}; struct node_t n2 = {2, NULL}, n1 = {1, &n2}; struct s {char data; struct t *sp} S; struct t {int data; struct s *tp} T; T.tp = &S; S.sp = &T;

Self-referential Structures: push/pop example (1) struct node_t { int data; struct node_t *previous;}; // node type of a stack (2) struct node_t *stack_ptr = NULL; // 'stack_ptr' variable points to the top node; // shared variable used by push(), pop()

Self-referential Structures: push/pop example (3) void push(int data) { (4) struct node_t *ptr; (5) ptr = malloc(sizeof *ptr); (6) ptr->data = data; (7) ptr->previous = stack_ptr; (8) stack_ptr = ptr; (9) }

Self-referential Structures: push/pop example (10) int pop(void) { (11) int data = stack_ptr->data; (12) struct node_t *ptr = stack_ptr; (13) stack_ptr = stack_ptr->previous; (14) free(ptr); (15) return data; (16) } Exercise Draw the memory diagrams before, during and after pop();

Typedef – 2 nd visit Examples of declarations – reminder typedef int length_t; // types int (old) and length_t (new) are synonyms typedef char *string_t; // string_t is a new type, synonym to type char * typedef int (*fct_t)(int); // fct_t is a new type, synonym to a 'pointer to a function // with one argument of type int and returning an int' A more complicated example of declarations (about recursion !) typedef struct node_t *stack_t; typedef struct node_t {int data; stack_t prev} node_t; Name overloading 'typedef struct x {int x} x;' is ok, but not recommended creates two new type keywords called node_t (a structure) and stack_t (a pointer to the structure) Examples of usage – reminder length_t size; string_t str, a[]; f(string_t); fct_t g;

Unions Example of a declaration (similar syntax as structures) union u_tag { int i; float x; char c;} u = 1; // only the first member can be initialized struct { char *data; union {int i; float r;} u; } tab[MAX]; Definition: a union is a variable that may hold (at different times) objects of different types and sizes Remarks 1.The variable u will be large enough to hold the largest of its members. 2.Members of a union are accessed just as for structures, with the '.' or '->' operators 3.It is the programmer's responsibility to keep track what type of value is currently stored in a union. 4.Unions may occur within structures and arrays, and vice versa, e.g.:

Bit-fields Definition: a bit-field is a set of adjacent bits within a word (today often 64-bits). Example of a bit-field variable 'flags' definition struct {unsigned int is_extern : 1; unsigned int is_static : 1; } flags; defines a variable flags that contains two 1-bit fields (the number following the colon represents the field width in bits). Syntax and access: based on structures. Assignment examples flags.is_extern = 1 // turn bit on flags.is_static = 0 // turn bit off

Bit-fields : virtual address example 'Virtual address' is a very important bit-field structure in all modern operating systems typedef struct { unsigned Offset :16; unsigned Page : 8; unsigned Segment : 6; unsigned UNUSED : 1; unsigned Supervisor: 1; } virtual_address; typedef struct { unsigned Supervisor: 1; unsigned UNUSED : 1; unsigned Segment : 6; unsigned Page : 8; unsigned Offset :16; } virtual_address; big-endian computer (packs bit-fields left to right) little-endian computer (packs bit-fields right to left) SSegmentPageOffset