Top Banner
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’
19

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 +

Dec 16, 2015

Download

Documents

Godwin Peters
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 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 +

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 2012KR6 + malloc + linked list: ~90’; Exercises: ~90’

Page 2: 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 +

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};

Page 3: 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 +

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

}

Page 4: 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 +

4

6.1 Basics of Structures: name overloading

Name OverloadingFollowing 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);

Page 5: 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 +

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

Page 6: 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 +

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

Page 7: 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 +

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;

}

Page 8: 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 +

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

Page 9: 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 +

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.

Page 10: 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 +

10

6.3 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))

Page 11: 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 +

11

6.4 Pointers to Structures6.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;

Page 12: 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 +

12

malloc, realloc, free

#include <stdlib.h>

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)

Exampleint *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

Page 13: 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 +

13

6.5 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()

Page 14: 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 +

14

6.5 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) }

Page 15: 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 +

15

6.5 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) }

ExerciseDraw the memory diagrams before, during and after pop();

Page 16: 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 +

16

6.7 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)

Page 17: 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 +

17

6.8 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

Remarks1. 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.:

Page 18: 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 +

18

6.9 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

Page 19: 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 +

19

6.9 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)

S Segment Page Offset

1 1 6 8 16