1 Lecture06: Complex Types 4/18/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.

Slides:



Advertisements
Similar presentations
An introduction to pointers in c
Advertisements

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.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
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.
Kernighan/Ritchie: Kelley/Pohl:
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
1 CSE 303 Lecture 12 structured data reading: Programming in C Ch. 9 slides created by Marty Stepp
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 6 : September 6.
Pointers| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2006 Slide 1 Pointers by Jumail Bin Taliba Faculty of Computer.
Programming in C Pointer Basics.
Lecture No: 16. The scanf() function In C programming language, the scanf() function is used to read information from standard input device (keyboard).
ARRAYS In this Lecture, we will try to develop understanding of some of the relatively complex concepts. The following are explained in this lecture with.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Outline Midterm results Static variables Memory model
1 Programming with Pointers Turgay Korkmaz Office: SB Phone: (210) Fax: (210) web:
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
Computer Science 210 Computer Organization Arrays.
Week 6 - Wednesday.  What did we talk about last time?  Exam 1!  And before that…  Review!  And before that…  Arrays and strings.
Lecture Contents Arrays and Vectors: Concepts of pointers and references. Pointer declarations and initialization. Pointer Operators. Dynamic Memory Allocation.
C STRUCTURES. A FIRST C PROGRAM  #include  void main ( void )  { float height, width, area, wood_length ;  scanf ( "%f", &height ) ;  scanf ( "%f",
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 26: Exam 2 Preview.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 23P. 1Winter Quarter Structs and Enumeration Lecture 23.
Chapter 11: Pointers Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 11 Pointers.
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 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic.
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:
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Spring 2005, Gülcihan Özdemir Dağ Lecture 11, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 11 Outline 11.1.
 Structures are like arrays except that they allow many variables of different types grouped together under the same name. For example you can create.
Data Structure and c K.S.Prabhu Lecturer All Deaf Educational Technology.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 13: Data structures in C.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
CPT: Types/ Computer Programming Techniques Semester 1, 1998 Objective of these slides: –to look at how new types can be created 6. User-defined.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
POINTERS Introduction to Systems Programming - COMP 1002, 1402.
Pointers PART - 2. Pointers Pointers are variables that contain memory addresses as their values. A variable name directly references a value. A pointer.
1 2/2/05CS250 Introduction to Computer Science II Pointers.
1 Lecture10: Structures, Unions and Enumerations 11/26/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
CSE 251 Dr. Charles B. Owen Programming in C1 Intro to Arrays Storing List of Data.
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.
Pointers A pointer type variable holds the address of a data object or a function. A pointer can refer to an object of any one data type; it cannot refer.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Chapter 6. Character String Types It is one in which the values consists of sequences of characters. How to Define a variable contain a string? In a programming.
What do I need to Know For My Assignment?. C Pointer Review To declare a pointer, we use the * operator. This is similar to but different from using *
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
CS 61C: Great Ideas in Computer Architecture C Pointers Instructors: Vladimir Stojanovic & Nicholas Weaver 1.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Chapter 8 Arrays, Strings and Pointers
Chapter 6 – Data Types CSCE 343.
Computer Science 210 Computer Organization
CSE 220 – C Programming Pointers.
Student Book An Introduction
Lecture 6 C++ Programming
Computer Science 210 Computer Organization
14th September IIT Kanpur
הגדרת משתנים יום שלישי 27 נובמבר 2018
Programming in C Pointer Basics.
EECE.2160 ECE Application Programming
Outline Defining and using Pointers Operations on pointers
Programming in C Pointer Basics.
Chapter 1: Introduction to Data Structures(8M)
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Programming in C Pointer Basics.
Presentation transcript:

1 Lecture06: Complex Types 4/18/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C

Administrative Items Midterm exam in class on 4/25 –Cover from the start to Pointers and Arrays Assignment #6 due on 5/2 r, long double, etc. 2

Complex Types Structures –User-defined combinations of other types Enumerations –User-defined weekday: sunday, monday,... Unions –Same data, multiple interpretations Arrays and pointers of the above Function pointers 3

Preliminary types we have learned Integer –short –int –long long int Real number –float –double Character –char String –char[] 4

Structure example 1: student Structures aggregate variables of different types –Defined with the keyword struct Example struct student { int id; int year; char grade; }; void main() { struct student s; s.id = 10001; s.year = 2011; s.grade = 'A'; } 5

Structure example 2: 2-D Points struct point { double x; double y; }; double distance(struct point p1, struct point p2) { double dx = p1.x - p2.x; double dy = p1.y - p2.y; return sqrt(dx * dx + dy * dy); } 6 void main() { struct point a; struct point b; a.x = 12.0; a.y = 42.0; b.x = 15.0; b.y = 36.0; printf(“The distance is %lf”, distance(a, b) ); return 0; }

Structure Syntax 7 To define a structure Definition struct structure_name { /* list of variable declarations */ }; To declare a variable of the new structure type Example void main() { struct structure_name variable_name; } The struct keyword is required in both places

Structures and typedef To avoid the struct keyword, use a typedef Create alias for struct student called student_t Example (revised from example 1) struct student { int id; int year; char grade; }; typedef struct student student_t; void main() { student_t s; s.id = 10001; s.year = 2011; s.grade = 'A'; } 8

Structures and typedef // a shortcut to define structure typedef struct point { double x; double y; }; double distance(point p1, point p2) { double dx = p1.x - p2.x; double dy = p1.y - p2.y; return sqrt(dx * dx + dy * dy); } 9 void main() { point a = {12.0, 42.0}; point b = {15.0, 36.0}; printf(“The distance is %lf”, distance(a, b) ); return 0; } Example (revised from example 2)

Structures in C C treats structures as if they were primitive data types –i.e. not like reference types (e.g. in Java) –Passing a structure as an argument to a function means that a temporary copy is made of the entire structure –Assignments do a deep copy of the entire structure Example void reset(point p) { p.x = p.y = 0; } void main() { point a; a.x = 12.0; a.y = 42.0; printf(“before: [%.1lf, %.1lf]\n", a.x, a.y); // a = 12.0, 42.0 reset(a); printf(“after: [%.1lf, %.1lf]\n", a.x, a.y); // a = ?, ? } 10

Structures in C C treats structures as if they were primitive data types –i.e. not like reference types (e.g. in Java) –Passing a structure as an argument to a function means that a temporary copy is made of the entire structure –Assignments do a deep copy of the entire structure Example void main() { point a; a.x = 12.0; a.y = 42.0; point b = a; printf(“before: [%.1lf, %.1lf]\n", b.x, b.y); // b = 12.0, 42.0 b.x = 0; printf(“after: [%.1lf, %.1lf]\n", b.x, b.y); // a = 0.0, 42.0 } 11

Pointers and Arrays Access array elements using pointers 12 void main() { int a[] = {3, 7, -1, 4, 6}; int i; double mean = 0; // compute mean of values in a for (i = 0; i < 5; ++i) { mean += *(a + i); } mean /= 5; printf("Mean = %.2f\n", mean); }

Pointers and Arrays Access array elements using pointers 13 void main() { int a[5] = {3, 7, -1, 4, 6}; int i; double mean = 0.0; // compute mean of values in a for (i = 0; i < 5; ++i) { mean += a[i]; } mean /= 5.0; printf("Mean = %.2f\n", mean); }

Pointers and Arrays What is *(a + i)? 14 for (i = 0; i < 5; ++i) { mean += *(a + i); } Try this: int a[5]; // print the address of array a printf("%d\n", a); // print the address of a[0] printf("%d\n", &a[0]); // print the address of a[1] printf("%d\n", &a[1]); // test what is “a + 1” printf("%d\n", a + 1);

Structures and Function Calls Function calls with structure arguments can be expensive bytes must be copied typedef struct { char name[10000]; int id; } person; void print_person(person p) { printf("%d %s\n", p.id, p.name); } void main() { person a = {"Mike Smith", 1234}; print_person(a); } 15

Solution Use pointers. Only the address of the structure is copied, not the entire structure. Use &s to get the address of a structure s Use *p to get the structure pointed by p Use (*p).field to access a field of the structure Or a cleaner syntax: –p->field 16

Pointers to Structures typedef struct { char name[10000]; int id; } person; void print_person(person *p) { printf("%d %s\n", p->id, p->name); } void main() { person a = {"Mike Smith", 1234}; print_person(&a); } 17

Pointers to Structure typedef struct { char name[10000]; int id; } person; void print_person(person *p) { printf("%d %s\n", p->id, p->name); } void main() { person *p; p = (person *) malloc(sizeof(person)); strcpy(p->name, "Mike Smith"); p->id = 1234; print_person(&a); free(p); } 18

What is #define ? #define SIZE 1000 int main() { int array[SIZE]; for (int i = 0; i < SIZE; i++) array[i] = 0; return 0; } 19 Easy to map a number into a meaningful word Common usage 1:

What is #define ? #define sun 0 #define mon 1 #define tue 2 #define wed 3 #define thu 4 #define fri 5 #define sat 6 20 Easy to map a number into a meaningful word Common usage 2: int main() { int week; scanf("%d", &week); if (week == wed) { // do something } return 0; }

What is #define ? #define FIVE #define SIX int main() { printf("%d\n", FIVE * SIX); return 0; } 21 #define can also be dangerous!! Common error:

Enumerations enum days {mon, tue, wed, thu, fri, sat, sun}; // Same as: // #define mon 0 // #define tue 1 //... // #define sun 6 enum days {mon = 3, tue = 8, wed, thu, fri, sat, sun}; // Same as: // #define mon 3 // #define tue 8 // #define wed 9 //... // #define sun 13 22

Enumerations enum days day; // Same as: int day; for (day = mon; day <= sun; ++day) { if (day == sun) { printf("Sun\n"); } else { printf("day = %d\n", day); } 23

Enumerations Basically integers Can use in expressions like this Makes code easier to read Cannot get string equiv. Caution: day++ will always add 1 even if enum values aren't contiguous. 24

Creating Your Own Types C lets you name your own types using typedef Example typedef double scalar; scalar add(scalar a, scalar b) { return a + b; } typedef syntax –As if you're declaring a variable of the type you want to redefine –Give the variable the name of the new type –Put typedef in front 25

More on typedef typedef double scalar; typedef scalar vector[10]; scalar add_scalars(scalar a, scalar b) { return a + b; } void add_vectors(vector result, vector a, vector b) { int i; for (i = 0; i < 10; ++i) { result[i] = a[i] + b[i]; } 26

Structures and the Heap So far we've been storing structures on the stack Structures can also be stored on the heap –Call malloc() to request a memory region of the correct size (Use sizeof to determine the correct size) –Cast the pointer returned by malloc to a pointer to the structure –Free the region when the structure is no longer needed 27

Union A union is a variable that stores objects of dierent types –But it can only store one object at a time –Like a structure, but all fields start at offset 0 e.g. You have a floating point number –Sometimes you want to treat it as a oat –Sometimes you want to treat it as an int –Sometimes you want to treat it as a char array Example union new_float { float float_view; int int_view; char array_view[4]; }; 28

Example union new_float { float float_view; int int_view; char array_view[4]; }; void main() { union new_float f; f.float_view = 3.7; printf("%f %d %c %c %c %c\n", f.float_view, f.int_view, f.array_view[0], f.array_view[1], f.array_view[2], f.array_view[3]); } 29

Function Pointers int min(int a, int b); int max(int a, int b); int foo(int do_min) { int (*func)(int, int); // declaring func. ptr if (do_min) { func = min; } else { func = max; } return func(10, 20); // indirect call } 30

Function Pointers Points to a function Has a *-type of the function it points to 31

Exercise 1 Problem: –I walked down the street one day and found n stores. I wrote down the names of these stores. Can you tell me when I went back, what store would I meet first during the way? Can you list these n stores in order? 32 Program: –enter how many stores you met: 5 store 1: seven store 2: watsons store 3: starbucks store 4: chanel store 5: coach from the way you went back, you will met: coach chanel starbucks watsons seven

Exercise 2 Problem: –Given a list of student grading information, can you tell me who is the first place? 33 Program: –enter how many students: 3 s1 name: Jonn s1 english: 75 s1 chinese: 88 s2 name: Many s2 english: 69 s2 chinese 62 s3 name: MrTop s3 english: 100 s3 chinese: 100 The first place is MrTop who got 200 points in total!

Explaination about Assignment #6 34 Pointer array void main() { struct card_t* deck[52]; fill_deck(deck); print_deck(deck); } ♤A♤A ♤2♤2 ♤3♤3 ♤4♤4 ♤5♤5 ♤6♤6 ♤7♤7 ♤8♤8 ♤9♤9

Explaination about Assignment #6 35 Pointer array void main() { struct card_t* deck[52]; fill_deck(deck) shuffle(deck); print_deck(deck); } ♤A♤A ♤2♤2 ♤3♤3 ♤4♤4 ♤5♤5 ♤6♤6 ♤7♤7 ♤8♤8 ♤9♤9

Explaination about Assignment #6 36 Pointer array void main() { struct card_t* deck[52]; fill_deck(deck) shuffle(deck); print_deck(deck); } ♤A♤A ♤2♤2 ♤3♤3 ♤4♤4 ♤5♤5 ♤6♤6 ♤7♤7 ♤8♤8 ♤9♤9