C Structures Self-referencing Card Shuffling Unions. C Structures CS Prof. Jonathan Ventura. Prof. Jonathan Ventura C Structures

Similar documents
CS132 Algorithm. Instructor: Jialiang Lu Office: Information Center 703

OBJECT ORIENTED PROGRAMMING USING C++

Fundamentals of Programming. Lecture 12: C Structures, Unions, Bit Manipulations and Enumerations

Chapter 6 - Pointers

C Pointers. sizeof Returns size of operand in bytes For arrays: size of 1 element * number of elements if sizeof( int ) equals 4 bytes, then

C Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review

Introduction. Structures, Unions, Bit Manipulations, and Enumerations. Structure. Structure Definitions

Pointers and Strings Prentice Hall, Inc. All rights reserved.

Pointers. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Chapter 8 STRUCTURES IN C

Pointers and Structure. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

C Pointers Pearson Education, Inc. All rights reserved.

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

Programming for Engineers Structures, Unions

Programming for Engineers Pointers

Darshan Institute of Engineering & Technology for Diploma Studies Unit 5

Subject: Fundamental of Computer Programming 2068

C Pointers. CS 2060 Week 6. Prof. Jonathan Ventura

Chapter 5 - Pointers and Strings

Chapter 5 - Pointers and Strings

More Pointers Week 11

COMP 2355 Introduction to Systems Programming

공학프로그래밍언어 (PROGRAMMING LANGUAGE FOR ENGINEERS) -STRUCTURE- SPRING 2015 SEON-JU AHN, CNU EE

ET156 Introduction to C Programming

Files and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060

Lecture 05 POINTERS 1

Arrays Arrays and pointers Loops and performance Array comparison Strings. John Edgar 2

Structures. Basics of Structures (6.1) EECS l Now struct point is a valid type. l Defining struct variables: struct point { int x; int y; };

Principles of C and Memory Management

Review Questions II KEY

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

Language comparison. C has pointers. Java has references. C++ has pointers and references

Homework 3. Due: Feb 25, 23:59pm. Section 1 (20 pts, 2 pts each) Multiple Choice Questions

Data Representation and Storage

C Programming Review CSC 4320/6320

Kurt Schmidt. October 30, 2018

C Structures, Unions, Bit Manipulations, and Enumerations

Procedural programming with C

CS 61c: Great Ideas in Computer Architecture

CS113: Lecture 5. Topics: Pointers. Pointers and Activation Records

MYcsvtu Notes LECTURE 34. POINTERS

Lecture 02 Summary. C/Java Syntax 1/14/2009. Keywords Variable Declarations Data Types Operators Statements. Functions

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

Chapter 10 C Structures, Unions, Bit Manipulations

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type

10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013

Fundamental of Programming (C)

Computer Systems Principles. C Pointers

Programación de Computadores. Cesar Julio Bustacara M. Departamento de Ingeniería de Sistemas Facultad de Ingeniería Pontificia Universidad Javeriana

Fundamentals of Programming Session 24

IPC144 - Introduction to Strings. array of characters is an array, each element of which has a character data type.

Relationship between Pointers and Arrays

The C Programming Language Part 4. (with material from Dr. Bin Ren, William & Mary Computer Science, and

8. Structures, File I/O, Recursion. 18 th October IIT Kanpur

C Characters and Strings

Pointers. 10/5/07 Pointers 1

C Program Development and Debugging under Unix SEEM 3460

C: How to Program. Week /Mar/05

Pointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays

CSE 230 Intermediate Programming in C and C++

EM108 Software Development for Engineers

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, SPRING 2013

ANSI C Reserved Words

Structures. Today s Goals. Structure Operations. Structure Type Declaration. Struct Instance. typedef. CS246 Lec12. Structures

Outline Arrays Examples of array usage Passing arrays to functions 2D arrays Strings Searching arrays Next Time. C Arrays.

A pointer is a variable just like other variable. The only difference from other variables is that it stores the memory address other variables.

Basic and Practice in Programming Lab7

Operating Systems 2INC0 C course Pointer Advanced. Dr. Ir. Ion Barosan

Pointers, Dynamic Data, and Reference Types

Intermediate Programming, Spring 2017*

Data Representation and Storage. Some definitions (in C)

CS24 Week 2 Lecture 1

ECE 264 Exam 2. 6:30-7:30PM, March 9, You must sign here. Otherwise you will receive a 1-point penalty.

Problem 2 Add the two 2 s complement signed 8-bit values given below, and express your answer in decimal.

CS349/SE382 A1 C Programming Tutorial

CSC231 C Tutorial Fall 2018 Introduction to C

a) (5 points) What is the output of the following code sequence? int *ptr = 0x1050; printf ("%x\n", ptr--); printf ("%x\n", ptr);

7. Arrays, More Java Looping

2/28/2018. Overview. The C Programming Language Part 4. Pointers. Pointers. Pointers. Pointers

Content. In this chapter, you will learn:

//main.cpp. using namespace std;

CS Introduction to Programming Midterm Exam #2 - Prof. Reed Fall 2015

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

typedef int Array[10]; String name; Array ages;

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

COMS W3101 Programming Language: C++ (Fall 2015) Ramana Isukapalli

!"#$% &'($) *+!$ 0!'" 0+'&"$.&0-2$ 10.+3&2),&/3+, %&&/3+, C,-"!.&/+"*0.&('1 :2 %*10% *%7)/ 30'&. 0% /4%./

MCA Semester 1. MC0061 Computer Programming C Language 4 Credits Assignment: Set 1 (40 Marks)

Structures, Unions Alignment, Padding, Bit Fields Access, Initialization Compound Literals Opaque Structures Summary. Structures

Lesson #8. Structures Linked Lists Command Line Arguments

IV Unit Second Part STRUCTURES

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012

Bit Manipulation in C

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

BBM#101# #Introduc/on#to# Programming#I# Fall$2013,$Lecture$12$

Fundamental of Programming (C)

Transcription:

Self-referencing Card Shuffling Unions CS 2060

Self-referencing Card Shuffling Unions : struct C enables us to aggregate diverse data types into a structure: struct Employee { char first_name[20]; char last_name[20]; unsigned int age; char gender; double hourly_salary; ; A struct is defined outside of any function. Note the construction with struct, the name, brackets, and semi-colon.

Self-referencing Card Shuffling Unions : struct To define a struct variable: int main() { struct Employee employee1; strcpy( employee1.first_name, "Jane" ); strcpy( employee1.last_name, "Doe" ); employee1.age = 22; employee1.gender = f ; employee1.hourly_salary = 20; Member variables are accessed using the. operator.

Self-referencing Card Shuffling Unions Relationship to Java/C++ classes A struct is similar to a class as in Java, C++, Python, C#, etc. However, a C struct cannot have member functions (methods) it can only have member variables. It is merely a convenient way to organize a block of memory.

Self-referencing Card Shuffling Unions struct example struct Message { char *sender; // sender IP address char *recipient; // recipient IP address size_t data_size; // number of bytes char *data; // data int timeout; // network timeout ; int sendmessage( const struct Message *msg ); int recvmessage( struct Message *msg );

Self-referencing Card Shuffling Unions Initializing a struct It is possible to initialize a struct with an initializer array: struct DictionaryEntry { char *word; char *definition; int scrabble_score; ; DictionaryEntry entry1 = { "apple", "a fruit", 9 ;

Self-referencing Card Shuffling Unions Using typedef It is convenient to use typedef to make the struct into a named data type: typedef struct { float x, y; Point2f; int main() { Point2f pt; pt.x = 10; pt.y = 20; With the typedef we don t need to write struct before the name when defining variables.

Self-referencing Card Shuffling Unions struct arrays and pointers We can make arrays and pointers of structs: Point2f points[10]; Point2f *ptr = points; ptr->x = 10; ptr->y = 20; ptr++; Note the use of -> to directly access member variables with a struct pointer. ptr->x = 10; (*ptr).x = 10; // equivalent

Self-referencing Card Shuffling Unions sizeof sizeof tells us the size of the entire structure: Point2f points[10]; memset( points, sizeof(point2f)*10, 0 ); What does sizeof(point2f) return? What does this code do?

Self-referencing Card Shuffling Unions Passing a struct to a function We can pass a struct by value or by reference: void sendmessagebyvalue( Message msg ); void sendmessagebyreference( Message *msg ); Why is pass-by-reference (using a pointer) preferred?

Self-referencing Card Shuffling Unions Passing a struct to a function We can pass a struct by value or by reference: void sendmessagebyvalue( Message msg ); void sendmessagebyreference( Message *msg ); Pass-by-value will make a copy of the structure, which might be a large block of memory. Pass-by-reference (using a pointer) will not make a copy, so it is faster and more memory-efficient.

Self-referencing Card Shuffling Unions Passing a struct to a function structs are useful to package data together and reduce arguments to functions: void sendmessagelong( char *sender, char *recipient, size_t data_size, char *data, int timeout ); void sendmessageshort( Message *msg ); Using a struct, the data stays together and the code is less messy.

Self-referencing Card Shuffling Unions struct arrays struct arrays are also useful to keep data together: char * words[10]; char * definitions[10]; int scrabble_scores[10]; // OR: struct DictionaryEntry entries[10]; Again, with a struct, the data stays together and the code is less messy.

Self-referencing Card Shuffling Unions struct example typedef struct { char name[10]; int score; Player; void incrementplayerscore( Player *player, int score ) { player->score += score; void printscoreboard( int nplayers, Player players[] ) { for ( int i = 0; i < nplayers; i++ ) { printf("%15s",players[i].name); puts(""); for ( int i = 0; i < nplayers; i++ ) { printf("%15d",players[i].score);

Self-referencing Card Shuffling Unions struct example int main() { Player players[4]; puts("enter player names:"); for ( int i = 0; i < 4; i++ ){ scanf( "%10s", players[i].name ); int round = 1; int next_player = 0; while ( 1 ) { printf("*** ROUND %d ***\n",round); printf("enter score for player %s:\n",players[next_player].name); int score; if ( scanf("%d",&score)!= 1 ) break; incrementplayerscore(&players[next_player],score); next_player = (next_player+1)%4; printscoreboard(4,players);

Self-referencing Card Shuffling Unions Self-referencing structures A struct can have a member variable whose type is a pointer to the struct itself: struct Employee { char firstname[20]; char lastname[20]; struct Employee *manager; ; Here the manager field points to an struct Employee. Only a self-referencing pointer is allowed, not an actual struct Employee.

Self-referencing Card Shuffling Unions Self-referencing example struct Employee { char *firstname; char *lastname; struct Employee *manager; ; void printemployeeinfo( struct Employee *e ); int main() { struct Employee boss = { "The", "Boss", NULL ; struct Employee jane = { "Jane", "Doe", &boss ; struct Employee john = { "John", "Doe", &boss ; printemployeeinfo( &boss ); printemployeeinfo( &jane ); printemployeeinfo( &john );

Self-referencing Card Shuffling Unions Self-referencing example void printemployeeinfo( const Employee *e ) { printf("first name: %s\n", e->firstname ); printf("last name: %s\n", e->lastname ); printf("manager: %s\n", (e->manager)? e->manager->lastname : "nobody" ); puts("");

Self-referencing Card Shuffling Unions Self-referencing example struct Word { char *word; char *definition; struct Word *synonyms[10]; ; void printword( struct Word *w ) { printf("word: %s\n",w->word); printf("definition: %s\n",w->definition); printf("synonyms:\n"); for ( int i = 0; i < 10; i++ ) { if ( w->synonyms[i] == NULL ) break; printf("\t%s\n", w->synonyms[i]->word );

Self-referencing Card Shuffling Unions Card shuffling example typedef struct { const char *face; const char *suit; Card; const char * kfaces[] = { "Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" ; const char * ksuits[] = { "Hearts", "Diamonds", "Clubs", "Spades" ; void filldeck( Card deck[] ); void shuffle( Card deck[] ); void deal( Card deck[] );

Self-referencing Card Shuffling Unions Card shuffling example void filldeck( Card deck[] ) { for ( int i = 0; i < 52; i++ ) { deck[i].face = kfaces[i % 13]; deck[i].suit = ksuits[i / 13];

Self-referencing Card Shuffling Unions Card shuffling example void shuffle( Card deck[] ) { for ( int i = 0; i < 52; i++ ) { int j = rand() % 52; // swap cards Card temp = deck[i]; deck[i] = deck[j]; deck[j] = temp;

Self-referencing Card Shuffling Unions Card shuffling example void deal( Card deck[] ) { for ( int i = 0; i < 52; i++ ) { printf("%s of %s\n", deck[i].face, deck[i].suit );

Self-referencing Card Shuffling Unions Card shuffling example int main() { Card deck[52]; srand(time(null)); filldeck( deck ); shuffle( deck ); deal( deck );

Self-referencing Card Shuffling Unions Unions A union is like a struct, except all member variables share the same storage space! union Number { int integer; float real; ; Here, integer and real actually overlap in memory. sizeof(union Number) = 4 bytes.

Self-referencing Card Shuffling Unions Union example union Number { int integer; float real; ; int main() { union Number n; n.integer = 100; printf("as int: %d\n",n.integer); printf("as float: %f\n",n.real); puts(""); n.real = 100.0; printf("as int: %d\n",n.integer); printf("as float: %f\n",n.real); puts("");

Self-referencing Card Shuffling Unions Unions A union might be useful to save space, if you need the flexibility to store one of many data types. Another use is to break an integer into bytes: union UInt { unsigned int integer; unsigend char bytes[4]; ; Here, integer and bytes overlap in memory. sizeof(union Number) = 4 bytes.

Self-referencing Card Shuffling Unions Union example #include <stdio.h> union UInt { unsigned int integer; unsigned char bytes[4]; ; int main() { union UInt n; n.integer = 1; for ( int i = 0; i < 32; i++ ) { printf("%16u %03d %03d %03d %03d\n", n.integer, n.bytes[0], n.bytes[1], n.bytes[2], n.bytes[3] ); n.integer *= 2;