010.133 Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 5.

Slides:



Advertisements
Similar presentations
Pointers.
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.
Dynamic memory allocation
Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
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.
Structures Spring 2013Programming and Data Structure1.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
Agenda  Review: pointer & array  Relationship between pointer & array  Dynamic memory allocation.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures.
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.
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:
Winter2015 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University C: Advanced Topics.
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
Pointers Chapters 6+9 in ABC. abp 12 int a = 1, b = 2, *p; & - reference operator (address) * - dereference operator (value) p = &a; // *p is now 1 abp.
1 CS 201 Dynamic Data Structures Debzani Deb. 2 Run time memory layout When a program is loaded into memory, it is organized into four areas of memory.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Pointers Applications
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Pointers| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2006 Slide 1 Pointers by Jumail Bin Taliba Faculty of Computer.
Review C++ exception handling mechanism Try-throw-catch block How does it work What is exception specification? What if a exception is not caught?
CS3012: Formal Languages and Compilers The Runtime Environment After the analysis phases are complete, the compiler must generate executable code. The.
Introduction to Data Structures Systems Programming.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
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.
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
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.
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.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 4.
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.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
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.
Introduction to Data Structures Systems Programming Concepts.
ECE Application Programming
Topics memory alignment and structures typedef for struct names bitwise & for viewing bits malloc and free (dynamic storage in C) new and delete (dynamic.
ECE Application Programming Instructors: Dr. Michael Geiger & Nasibeh Nasiri Fall 2015 Lecture 31: Structures (cont.) Dynamic memory allocation.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 1.
Computer Programming for Engineering Applications ECE 175 Intro to Programming.
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
Arrays, Strings, and Memory. Command Line Arguments #include int main(int argc, char *argv[]) { int i; printf("Arg# Contents\n"); for (i = 0; i < argc;
ENEE150 – 0102 ANDREW GOFFIN Dynamic Memory. Dynamic vs Static Allocation Dynamic  On the heap  Amount of memory chosen at runtime  Can change allocated.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
1 Linked List. 2 List A list refers to a sequence of data items  Example: An array The array index is used for accessing and manipulation of array elements.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Linked Lists Outline Introduction Self-Referential Structures.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
C Structures and Memory Allocation
Stack and Heap Memory Stack resident variables include:
Linked List :: Basic Concepts
5.13 Recursion Recursive functions Functions that call themselves
Introduction to Data Structures
Memory Allocation CS 217.
Pointers.
EECE.2160 ECE Application Programming
Review & Lab assignments
Linked List.
Programming Languages and Paradigms
C Structures and Memory Allocation
Pointers.
Presentation transcript:

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 5

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Structures A structure is a collection of one or more variables, possibly of different types Struct person introduces a structure which contains three members, i.e., name, age, and sex Person is called a structure tag Once the structure tag is defined, we can declare structure variables struct person per1, per2; struct person { char name[10]; int age; char sex; };

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Structure (contd.) A structure variable can be initialized by initializing its members struct person per1 = {“Lee”, 20, ‘f’};

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Operations on Structures A member of a structure variable is referred to by the following form: structure-variable.member For example, we can print the members of per1 as follows: printf("%s, %d, %c", per1.name, per1.age, per1.sex); A structure can be copied as a unit For example, per2 = per1; copies per1.name to per2.name, per1.age to per2.age, and per1.sex to per2.sex

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Operations on Structures (contd.) We can take the address of a structure with & pp is declared as a pointer to struct person, and the address of per1 is assigned to pp (i.e., pp points to per1 ) *pp means per1, and (*pp).name, (*pp).age, (*pp).sex refer to per1 ’s members struct person *pp; … pp = &per1;

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Operations on Structures (contd.) If pp is a pointer to a structure, an alternative notation to refer to a member is pp->structure-member pp->name, pp->age, and pp->sex refer to the members of per1

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Array of Structures When we need to maintain a list of persons, we can declare an array of structures: struct person per[10];

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Array of Structures (contd.) #include struct person { char name[10]; int age; char sex; }; void PrintPerson(struct person *pp) { printf("name: %s, age: %d, sex: %c\n", pp->name, pp->age, pp->sex); } int main(void) { int i; struct person per[3]={ {“Lee”, 20, 'f'}, {“Kim”, 25, 'm'}, {“Park”, 22, ‘f’} }; for (i=0; i<3; i++) PrintPerson(&per[i]); return 0; }

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Structure Example The following program declares a structure for complex numbers and a function for complex number multiplication #include struct complex { double x; double y; }; struct complex cmult(struct complex a, struct complex b) { struct complex c; c.x = a.x * b.x - a.y * b.y; c.y = a.x * b.y + a.y * b.x; return c; }

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Structure Example (contd.) int main(void) { struct complex a, b, c; printf("Enter a: "); scanf("%lf %lf", &a.x, &a.y); printf("Enter b: "); scanf("%lf %lf", &b.x, &b.y); c = cmult(a, b); printf("Mult: %f + %f i\n", c.x, c.y); return 0; }

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Typedef (revisited) typedef complex { double x; double y; } Complex;... Complex a, b, c;

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee The same syntax as structures But, members share storage Unions typedef union foo { int n; float r; } number; int main(void) { number m; m.n = 2345; printf(“n: %10d r: %16.10e\n”, m.n, m.r); m.r = 2.345; printf(“n: %10d r: %16.10e\n”, m.n, m.r); return 0; }

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee struct foo { int n; float r; } p; union foo { int n; float r; } q; Unions (contd.) n r p q nrnr

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee In the standard library (stdlib.h) To dynamically create storage for arrays, structures, and unions void* calloc( size_t n, size_t s ) Contiguous allocation Allocates contiguous space in memory with a size of n × s bytes The space is initialized with 0’s If successful, returns a pointer to the base of the space Otherwise, returns NULL Typically “ typedef unsigned int size_t; ” in stdlib.h x = calloc( n, sizeof( int )); calloc() and malloc()

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee void* malloc( size_t s ) Similar to calloc() Allocates contiguous space in memory with a size of s bytes without initialization x = malloc( n * sizeof( int )); calloc() and malloc() (contd.)

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee The programmer should explicitly return the space free( ptr ); Makes the space in memory pointer by ptr to be deallocated ptr must be the base address of space previously allocated calloc() and malloc() (contd.)

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Functions as Arguments Pointers to functions can be passed as arguments

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee (*f)(k) f : the pointer to a function *f : the function itself (*f)(k) : the call to the function All the following function prototypes are the same double sum_square(double f(double x), int m, int n); double sum_square(double f(double), int m, int n); double sum_square(double f(double), int, int); double sum_square(double (*f)(double), int, int); double sum_square(double (*)(double), int, int); double sum_square(double g(double y), int a, int b);

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee (*f)(k) (contd.)

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Ragged Arrays An array of pointers whose elements are used to point to arrays of varying sizes. char x[2][7] = {“abc”, “abcde” }; (normal arrays) char *p[2] = {“abc”, “abcde” }; (ragged arrays)

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Command-line Arguments to main() To communicate with the OS argc : the number of command line arguments argv : an array of strings The strings are the words that make up the command line argv[0] contains the name of the command itself

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Command-line Arguments (contd.)

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Command-line Arguments (contd.)

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Typical Compilation Phases

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Abstract Data Types An abstract data type is a collection of objects together with a collection of operations Lists, sets, and stacks are examples of abstract data types

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Abstract Data Types (contd.) A list is simply a list of elements a 1, a 2, …, and a k Two operations on the list Linsert(list, x) inserts element x into list Lsearch(list, x) searches list for element x We may define more operations such as Ldelete A set {a 1, a 2, …, a k } along with some set operations such as union and intersection can be an abstract data type A stack is an important abstract data type which has many applications in programming

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Linked Lists A linked list is a list of nodes linked by pointers A node of a linked list requires a structure It has two members element and next which is a pointer to struct node struct node { int element; struct node *next; };

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Linked Lists (contd.) Linsert(list, x) gets list, which is a pointer to a linked list, and element x as its input It inserts x at the front of the list Lsearch(list, x) gets list, which is a pointer to a linked list, and x as its input If x is in the list, it returns the pointer of the node that contains x; NULL otherwise

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Linked Lists (contd.) The next program creates a linked list by inserting elements, and searches it for an element x #include struct node { int element; struct node *next; };

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Linked Lists (contd.) struct node *Linsert(struct node *list, int x) { struct node *pnew; pnew = malloc(sizeof(struct node)); if (pnew == NULL) { printf(“malloc error\n”); return NULL; } pnew->element = x; pnew->next = list; return pnew; }

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Linked Lists (contd.) struct node *Lsearch(struct node *list, int x) { struct node *pn; for (pn = list; pn != NULL; pn = pn->next) if (pn->element == x) return pn; return NULL; }

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Linked Lists (contd.) void PrintList(struct node *list) { if (list == NULL) { printf(“\n”); return; } printf(“%d “, list->element); PrintList(list->next); }

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Linked lists (contd.) int main(void) { struct node *list = NULL; int x; while (1) { printf(“enter x (0 to terminate): “); scanf(“%d”, &x); if (x == 0) break; list = Linsert(list, x); } PrintList(list); printf(“enter x: “); scanf(“%d”, &x); if (Lsearch(list, x) != NULL) printf(“%d is in the list\n”, x); else printf(“%d is not in the list\n”, x); return 0; }

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Stacks A stack is a list of elements with the restriction that elements are inserted and deleted only at one place called the top

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Stacks (contd.) Fundamental stack operations are push and pop push(st, x) gets st, which is a pointer to a stack, and element x as its input It pushes x into the stack. pop(st) gets st, which is a pointer to a stack, and it pops and returns the element at the top

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Stacks (contd.) #include #define MAX 100 struct stack { int starray[MAX]; int top; };

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Stacks (contd.) struct stack *create(void) { struct stack *st; st = malloc(sizeof(struct stack)); if (st == NULL) { printf(“malloc error\n”); return NULL; } st->top = 0; return st; }

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Stacks (contd.) int is_empty(struct stack *st) { return st->top == 0; } void push(struct stack *st, int x) { if (st->top == MAX) { printf(“stack is full\n”); return; } st->starray[st->top++] = x; }

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Stacks (contd.) int pop(struct stack *st) { if (is_empty(st)) { printf(“stack is empty\n”); return; } return st->starray[--st->top]; }

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Stacks (contd.) int main(void) { struct stack *st; int x; st = create(); while (1) { printf(“enter x (0 to terminate): ”); scanf(“%d”, &x); if (x == 0) break; push(st, x); } while (!is_empty(st)) printf(“%d ”, pop(st)); printf(“\n”); return 0; }

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Programming style Programming style is a set of rules or guidelines for writing computer programs A good programming style is a subject matter, and thus it is difficult to define However, there are several elements common to many programming styles

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Programming style (contd.) Indentation helps identify control flows Blank lines can divide a program into logical units Also spaces should be used properly to enhance readability of programs Variable names and function names: names should carry appropriate meanings

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Programming style (contd.) Write clearly what you are doing in comments Modular design: use functions for independent tasks Write first in an easy-to-understand language, and then translate into a programming language