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 +

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 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.
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.
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Agenda  Review: pointer & array  Relationship between pointer & array  Dynamic memory allocation.
Structures, Unions, and Typedefs CIS 1057 Fall Structures, Unions, and Typedefs CIS 1057 Computer Programming in C Fall 2013 (Many slides based on/borrowed.
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 7 : September 8.
CP104 Introduction to Programming Structure II Lecture 32 __ 1 Data Type planet_t and Basic Operations Abstract Data Type (ADT) is a data type combined.
C Programming : Dynamic memory allocation & Structures 2008/11/19 Made by Jimin Hwa Edited and presented by Souneil Park
Kernighan/Ritchie: Kelley/Pohl:
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
Discussion: Week 3/26. Structs: Used to hold associated data together Used to group together different types of variables under the same name struct Telephone{
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
Structures, Unions, and Typedefs CS-2301 D-term Structures, Unions, and Typedefs CS-2301 System Programming D-term 2009 (Slides include materials.
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
CS 61C L4 Structs (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #4: Strings & Structs
Structures and UnionsCS-2301 B-term Structures and Unions CS-2301, System Programming for Non-majors (Slides include materials from The C Programming.
Computer Science 210 Computer Organization Pointers and Dynamic Storage.
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.
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.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
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.
6. More on Pointers 14 th September IIT Kanpur C Course, Programming club, Fall
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.
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.
 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)
Today’s Material Aggregate Data Types: Structures and Unions
+ 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.
POINTERS Introduction to Systems Programming - COMP 1002, 1402.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 5.
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.
ENEE150 – 0102 ANDREW GOFFIN Dynamic Memory. Dynamic vs Static Allocation Dynamic  On the heap  Amount of memory chosen at runtime  Can change allocated.
Structures CSE 2031 Fall March Basics of Structures (6.1) struct point { int x; int y; }; keyword struct introduces a structure declaration.
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
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)
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
Lecture 9 Structure 1. Concepts of structure Pointers of structures
CS 240 – Lecture 18 Command-line Arguments, Typedef, Union, Bit Fields, Pointers to Functions.
Memory Allocation CS 217.
EECE.2160 ECE Application Programming
Structures, Unions, and Typedefs
CS111 Computer Programming
Structures CSE 2031 Fall February 2019.
C Programming Lecture-8 Pointers and Memory Management
Structures CSE 2031 Fall April 2019.
Structures CSE 2031 Fall May 2019.
Structures EECS July 2019.
C Structures and Memory Allocation
Pointers, Dynamic Data, and Reference Types
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 + malloc + linked list (6.6 Table Lookup –– not treated in this course) 6.7 Typedef 6.8 Unions 6.9 Bit-fields Chap. 6 Structures + malloc + linked list Imperative and System Programming, B. Hirsbrunner, diuf.unifr.ch/pai/ip, Lecture 7 – 7 November 2012 KR6 + malloc + 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; 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]' this type, and -sets aside storage for them Example #define NKEYS (sizeof keytab / sizeof(struct key))

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;

12 malloc, realloc, free #include void *malloc(size_t size); void *realloc(void *ptr, size_t size) void free(void *ptr); malloc: allocates a memory of size bytes, and returns a pointer to the first element (a NULL pointer if the memory couldn't be allocated) Example int *ptr; ptr = malloc(sizeof(int)); ptr = realloc(ptr, sizeof(int)); free(ptr); realloc: changes the size of the object pointed to by ptr to size. The content will be unchanged up to the minimum of the old and new sizes. It returns a pointer with the same meaning as the one returned by malloc. free: deallocates the memory pointed by ptr, and previously allocated by malloc or realloc

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 = (struct node_t *) malloc(sizeof(struct node_t)); (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 Examples of declarations 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 * Examples of usage string_t str, a[], f(string_t); 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)

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 (often 32-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