1 Homework HW6 due class 22 K&R 6.6 K&R 5.7 – 5.9 (skipped earlier) Finishing up K&R Chapter 6.

Slides:



Advertisements
Similar presentations
Incomplete Structs struct B; struct A { struct B * partner; // other declarations… }; struct B { struct A * partner; // other declarations… };
Advertisements

Chapter 10 C Structures, Unions, Bit Manipulations and Enumerations Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc.
Programming in C Chapter 10 Structures and Unions
C Language.
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.
Chapter 6 Structures By C. Shing ITEC Dept Radford University.
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.
Copyright © 2000, Daniel W. Lewis. All Rights Reserved. CHAPTER 3 GETTING THE MOST OUT OF C.
Bit Field.
Review for Final Exam Dilshad M. NYU. In this review Arrays Pointers Structures Java - some basic information.
Pointer, malloc and realloc 1. Name entered was 6 char, not enough space to put null terminator 2 Array of char.
Programming in C Pointers and Arrays, malloc( ). 7/28/092 Dynamic memory In Java, objects are created on the heap using reference variables and the new.
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.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
1 Homework Turn in HW2 at start of next class. Starting Chapter 2 K&R. Read ahead. HW3 is on line. –Due: class 9, but a lot to do! –You may want to get.
Structures, Unions, and Typedefs CS-2301 D-term Structures, Unions, and Typedefs CS-2301 System Programming D-term 2009 (Slides include materials.
Pointers A pointer is a variable that contains memory address as its value. A variable directly contains a specific value. A pointer contains an address.
C structures and unions (Reek, Ch. 10) 1CS 3090: Safety Critical Programming in C.
Lecture 2 Pointers Pointers with Arrays Dynamic Memory Allocation.
Structures and UnionsCS-2301 B-term Structures and Unions CS-2301, System Programming for Non-majors (Slides include materials from The C Programming.
1 Inner Workings of Malloc and Free Professor Jennifer Rexford COS 217.
Data Representation and Alignment Topics Simple static allocation and alignment of basic types and data structures Policies Mechanisms.
Structures, Unions, and Typedefs CS-2303, C-Term Structures, Unions, and Typedefs CS-2303 System Programming Concepts (Slides include materials from.
Pointers Applications
Overview Working directly with memory locations is beneficial. In C, pointers allow you to: change values passed as arguments to functions work directly.
8. Structures, File I/O, Recursion 18 th October IIT Kanpur 1C Course, Programming club, Fall 2008.
IT253: Computer Organization Lecture 3: Memory and Bit Operations Tonga Institute of Higher Education.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
6. More on Pointers 14 th September IIT Kanpur C Course, Programming club, Fall
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
1 Exam / Homework Exam 1 in Class 10 –Open book / open notes HW3 due next class HW4 will be on-line soon. Finishing Chapter 2 of K&R. We will go through.
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.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
1 Homework HW5 due today Review a lot of things about allocation of storage that may not have been clear when we covered them in our initial pass Introduction.
Homework Finishing up K&R Chapter 6 today Also, K&R 5.7 – 5.9 (skipped earlier)
Data Structure and c K.S.Prabhu Lecturer All Deaf Educational Technology.
1 Homework HW4 due today HW5 is on-line Starting K&R Chapter 5 –Skipping sections for now –Not covering section 5.12.
Week 10 - Wednesday.  What did we talk about last time?  Linked list implementations  Started doubly linked lists.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
1 Homework / Exam Finishing K&R Chapter 5 today –Skipping sections for now –Not covering section 5.12 Starting K&R Chapter 6 next Continue HW5.
Topics memory alignment and structures typedef for struct names bitwise & for viewing bits malloc and free (dynamic storage in C) new and delete (dynamic.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 2 – August 23, 2001.
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.
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.
CS 31 Discussion, Week 7 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:30-1:30pm.
 Data Type is a basic classification which identifies different types of data.  Data Types helps in: › Determining the possible values of a variable.
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)
Java Programming Language Lecture27- An Introduction.
Windows Programming Lecture 03. Pointers and Arrays.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
1 Binghamton University Exam 1 Review CS Binghamton University Birds eye view -- Topics Information Representation Bit-level manipulations Integer.
C LANGUAGE MULTIPLE CHOICE QUESTION
CSCI206 - Computer Organization & Programming
Clear1 and Clear2 clear1(int array[], int size) { int i; for (i = 0; i < size; i += 1) array[i] = 0; } clear2(int *array, int size) {
14th September IIT Kanpur
CS 240 – Lecture 18 Command-line Arguments, Typedef, Union, Bit Fields, Pointers to Functions.
Homework Starting K&R Chapter 5 Good tutorial on pointers
Homework Continuing K&R Chapter 6.
Homework Continue with K&R Chapter 5 Skipping sections for now
Homework Finishing Chapter 2 of K&R. We will go through Chapter 3 very quickly. Not a lot is new. Questions?
C Structures and Memory Allocation
Presentation transcript:

1 Homework HW6 due class 22 K&R 6.6 K&R 5.7 – 5.9 (skipped earlier) Finishing up K&R Chapter 6

2 Table Lookup, K&R 6.6 struct for a linked list of names/definitions struct nlist {/* table entry */ struct nlist *next;/* link to next */ char *name;/* word name */ char *defn;/* word definition */ };

3 Table Lookup / Linked Lists Array of pointers to null terminated linked lists of structs defining table entries [0] [1] [2] [3] [4] 0 0 nlist array

4 Table Lookup / Linked List Hash function to select starting array element unsigned int hash (char *s) { for (hashval = 0; *s != ‘\0’; s++) hashval = *s + 31 * hashval; return hashval % HASHSIZE; } In lookup ( ), std code for following a linked list: for (ptr = head; ptr != NULL; ptr = ptr->next)

5 Multi-Dimensional Arrays Declare rectangular multi-dimensional array char a[2][3]; /* array [row] [column] */ NOTE: char a[2, 3] is INCORRECT! The rightmost subscript varies fastest as one looks at how data lies in memory: a[0][0], a[0][1], a[0][2], a[1][0], a[1][1],... It is the same as a one dimensional array [2] with each element being an array [3]

6 Multi-Dimensional Arrays Example of converting a month & day into a day of the year for either normal or leap years static char daytab[2][13] = { {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} }; Use a second row of day counts for leap year rather than perform a calculation for days in February daytab[1][1] is 31  same as daytab[0][1] daytab[1][2] is 29  not same as daytab[0][2]

7 Multi-Dimensional Arrays The array declared as char daytab[2][13] can be thought of as: char (daytab [2]) [13]; /* pg. 53 */ Each one dimensional array element ( daytab[0], daytab[1] ) is like array name - as if we declared: char daytab0 [13], daytab1 [13]; daytab[0] is in memory first, then daytab[1]

8 Multi-Dimensional Arrays daytab[0] and daytab[1] are arrays of 13 chars Now recall duality of pointers and arrays: (daytab [0])[n]  (*daytab)[n] (daytab [1])[n]  (*(daytab+1))[n] daytab is a pointer to an array of elements each of which is an array of size 13 chars

9 Multi-Dimensional Arrays But, these two declarations are not allocated memory the same way: char daytab[2][13];  26 char-sized locations char (*dp) [13];  1 pointer-sized location For the second declaration, code must set the pointer equal to an already defined array of [n] [13] dp = daytab; OR Use malloc to allocate memory for an array: dp = (char (*)[13]) malloc(2*13);

10 Multi-Dimensional Arrays static char daytab[2][13] = {... }; dp = daytab; daytab[0][2] == 28daytab[1][2] == 29 dp Array of 13 chars 1 char (*) [13] A pointer to an unspecified number of 13 char arrays dp = (char (*)[13]) malloc(2*13); Array of 13 chars (*dp)[2] == 28(*(dp + 1))[2] == 29 (*dp)[2] == ??(*(dp + 1))[2] == ??

11 Multi-Dimensional Arrays “Real” C programmers use pointers to pointers often and multidimensional arrays rarely Avoids worst case for memory allocation Example: In hw5, allocating lines array as a two dimensional array (compiler allocated): char lines [MAXLINE][MAXLEN]; Allocates 2000*1000 bytes = 2 Megabytes! However, code runs faster w/o malloc/free

12 Multi-Dimensional Arrays We could have declared lines and the pointers to lines in my hw5 solution as follows: static char lines[MAXLINE][MAXLEN]; static char (*first)[MAXLEN], /* size of the */ (*last)[MAXLEN], /* data type is */ (*end)[MAXLEN]; /* MAXLEN (1000) */ static int wrapped; We are using all compiler allocated memory We don’t malloc and free any memory!

13 Multi-Dimensional Arrays Function init_lineholder void init_lineholder(int nlines) { if (nlines > MAXLINE) nlines = MAXLINE; first = last = lines; end = lines + nlines; /* lines + 2Meg */ wrapped = 0; }

14 Multi-Dimensional Arrays Function insert_lines void insert_line(char *line) { strcpy(*last++, line); /* incr by 1K bytes */ if (wrapped) first = (++first >= end)? /* incr by 1K bytes */ lines : first; /* reset if needed */ if (last >= end) { last = lines; wrapped = 1; }

15 Multi-Dimensional Arrays Function print_lines void print_lines(void) { do { if (*first != NULL) printf("%s", *first); first = (++first >= end)? lines : first; } while (first != last); }

16 Multi-Dimensional Arrays ‘n’ ‘o’ ‘w’ ‘ ’ ‘i’ ‘s’ … ‘\0’ ‘f’ ‘o’ ‘r’ ‘ ’ ‘a’ ‘l’ ‘l’ ‘ ’… ‘\0’ MAXLINE MAXLEN Wasted Memory Space

17 typedef, K&R 6.7 typedef creates a new name for existing type typedef int Boolean; typedef char *String; Does not create a new type in any real sense No new semantics for the new type name! Variables declared using new type name have same properties as variables of original type

18 typedef Could have used typedef in section 6.5 like this: typedef struct tnode { char *word; int count; treeptr left; treeptr right; } treenode; typedef struct tnode *treeptr;

19 typedef Then, could have coded talloc ( ) as follows: treeptr talloc(void) { return (treeptr) malloc(sizeof(treenode)); }

20 typedef Used to provide clearer documentation: treeptr root; versus struct tnode *root; Used to create machine independent variable types: typedef int size_t;/* size of types */ typedef int ptrdiff_t; /* difference of pointers */

21 Unions, K&R 6.8 A Union is a variable that may hold objects of different types (at different times or for different instances of use) union u_tag { int ival; float fval; char *sval; } u;

22 Unions A union will be allocated enough space for the largest type in the list of possible types Same as a struct except all members have a zero offset from the base address of union u ivalfval*sval

23 Unions The operations allowed on unions are the same as operations allowed on structs: –Access a member of a union union u_tag x; x.ival = … ; –Assign to union of the same type union u_tag y; x = y;

24 Unions –Create a pointer to / take the address of a union union u_tag x; union u_tag *px = &x; –Access a member of a union via a pointer px->ival = … ;

25 Unions Program code must know which type of value has been stored in a union variable and process using correct member type DON’T store data in a union using one type and read it back via another type in attempt to get the value converted between types x.ival = 12;/* put an int in union */ float z = x.fval; /* don’t read as float! */

26 Bit-Fields, K&R 6.9 Bit fields are used to get a field size other than 8 bits (char), 16 bits (short on some machines) or 32 bits (long on most machines) Allows us to “pack” data one or more bits at a time into a larger data item in memory to save space, e.g. 32 single bit fields to an int Can use bit fields instead of using masks, shifts, and or’s to manipulate groups of bits

27 Bit-Fields Uses struct form: struct { unsigned int flg1 : 1; /* called a “bit field“ */ unsigned int flg2 : 1; /* ": 1"  "1 bit in length " */ unsigned int flg3 : 2; /* ": 2"  "2 bits in length" */ } flag; /* variable */ Field lengths must be an integral number of bits

28 Bit-Fields Access bit fields by member name same as any struct – just limited number of values flag.flg1 = 0; /* or = 1; */ flag.flg3 = 0; /* or = 1; = 2; =3; */

29 Bit-Fields Minimum size data item is implementation dependent, as is order of fields in memory Don’t make any assumptions about order!! Sample memory allocation: flags flags.flg1flags.flg2 flags.flg3 112