CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 12 – C: structs, linked lists, and casts.

Slides:



Advertisements
Similar presentations
CS 11 C track: lecture 7 Last week: structs, typedef, linked lists This week: hash tables more on the C preprocessor extern const.
Advertisements

Introduction to Linked Lists In your previous programming course, you saw how data is organized and processed sequentially using an array. You probably.
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.
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.
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:
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.
Structures C and Data Structures Baojian Hua
CS100A, Fall 1997, Lecture 241 CS100A, Fall 1997 Lecture 24, Tuesday 25 November (There were no written notes for lecture 23 on Nov. 20.) Data Structures.
Pointer. Warning! Dangerous Curves C (and C++) have just about the most powerful, flexible and dangerous pointers in the world. –Most other languages.
C and Data Structures Baojian Hua
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
C structures and unions (Reek, Ch. 10) 1CS 3090: Safety Critical Programming in C.
Miscellaneous topicsCS-2301 B-term Miscellaneous Topics CS-2301, System Programming for Non-majors (Slides include materials from The C Programming.
Adapted from Dr. Craig Chase, The University of Texas at Austin.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Chapter 7: Runtime Environment –Run time memory organization. We need to use memory to store: –code –static data (global variables) –dynamic data objects.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
CSE 425: Data Types II Survey of Common Types I Records –E.g., structs in C++ –If elements are named, a record is projected into its fields (e.g., via.
Functions, Pointers, Structures Keerthi Nelaturu.
Variables and Objects, pointers and addresses: Chapter 3, Slide 1 variables and data objects are data containers with names the value of the variable is.
Introduction to Java University of Sunderland CSE301 Harry R. Erwin, PhD.
Compiler Construction
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Programming in C Advanced Pointers. Pointers to Pointers Since a pointer is a variable type, a pointer may point to another pointer.Since a pointer is.
CSE 425: Data Types I Data and Data Types Data may be more abstract than their representation –E.g., integer (unbounded) vs. 64-bit int (bounded) A language.
(1 - 1) Introduction to C Data Structures & Abstract Data Types Instructor - Andrew S. O’Fallon CptS 122 (August 26, 2015) Washington State University.
1 Records Record aggregate of data elements –Possibly heterogeneous –Elements/slots are identified by names –Elements in same fixed order in all records.
C++ Memory Overview 4 major memory segments Key differences from Java
Copyright © Curt Hill Structured Data What this course is about.
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.
 2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
RUN-Time Organization Compiler phase— Before writing a code generator, we must decide how to marshal the resources of the target machine (instructions,
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Data Type. Syntax Rules Recap keywords breakdoubleifsizeofvoid caseelseintstatic..... Identifiers not#me123th scanfprintf _idso_am_igedd007 Constant ‘a’‘+’
The Cn Language over view The Cn language strongly on ANSI C. So if you are familiar with ANCI it is not so tough to deal with Cn language. Basic Data.
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
Generic lists Vassilis Athitsos. Problems With Textbook Interface? Suppose that we fix the first problem, and we can have multiple stacks. Can we have.
Structures and Unions in C Alan L. Cox
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Topics memory alignment and structures typedef for struct names bitwise & for viewing bits malloc and free (dynamic storage in C) new and delete (dynamic.
Programming Fundamentals. Overview of Previous Lecture Phases of C++ Environment Program statement Vs Preprocessor directive Whitespaces Comments.
CS536 Types 1. Roadmap Back from our LR Parsing Detour Name analysis – Static v dynamic – Scope Today – Type checking 2 Scanner Parser Tokens Semantic.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 10 – C: the heap and manual memory management.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Weekly C-minar Week 0. Today: Steps of the compile Basic inclusion/syntax rules Low-cost containment Debugging.
Introduction to Computers and Programming Class 24 Structures (structs) Professor Avi Rosenfeld.
Pointers & References. Pointers Pointer arithmetic Pointers and arrays Pointer-related typedef’s Pointers and const References.
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.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 20 – C++ Subclasses and Inheritance.
CSE 333 Systems Programming Hal Perkins Winter 2016 Bonus Lecture– Function Pointers and Objects in C.
Basic Data Types & Memory & Representation. Basic data types Primitive data types are similar to JAVA: char int short long float double Unlike in JAVA,
CS 100Lecture 221 Announcements P5 due Thursday Final Exam: Tuesday August 10, 8AM - 10AM, Olin 155 Want references? Remember to drop off a picture and.
Java Programming Language Lecture27- An Introduction.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
CSE 374 Programming Concepts & Tools
CSE 374 Programming Concepts & Tools
CSE 374 Programming Concepts & Tools
C Basics.
Conversions of the type of the value of an expression
Pointers C#, pointers can only be declared to hold the memory addresses of value types int i = 5; int *p; p = &i; *p = 10; // changes the value of i to.
CISC/CMPE320 - Prof. McLeod
Java Programming Language
CSE 303 Concepts and Tools for Software Development
Lecture 7: Types (Revised based on the Tucker’s slides) 10/4/2019
CSE 303 Concepts and Tools for Software Development
Presentation transcript:

CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 12 – C: structs, linked lists, and casts

Where we are We’ve seen most of the basic stuff about C, but we still need to look at structs (aka records or objects without methods) and linked data structures –Understand the code posted with today’s lecture; we won’t have time to walk through all the details Next: Rest of the C preprocessor (# stuff, macros), building multi-file programs Then: more programming tools (make) That will set us up for the next programming project –Which will start right after Monday’s midterm 2

structs A struct is a record (i.e., a collection of data fields) A pointer to a struct is like a Java object with no methods x.f is for field access. (if is x not a pointer – new!) (*x).f in C is like x.f in Java. (if x is a pointer) x->f is an abbreviation for (*x).f There is a huge difference between a struct (value) parameter and a pointer to a struct There is a huge difference between local variables that are structs and those that are pointers to structs Again, left-expressions evaluate to locations (which can be whole struct locations or just a field’s location) Again, right-expressions evaluate to values (which can be whole structs or just a field’s contents) 3

struct example A typical struct definition looks like: struct person_info { char * name; int age; } The identifier person_info after “struct” is not a type name, it is a struct tag. The “type” of this struct is struct person_info. –So type names ( int, char ) and struct tags are not the same kind of names 4

C parameters - revisited C has a uniform rule for parameters (almost): When a function is called, each parameter is initialized with a copy of the corresponding argument (int, char, ptr,…) –This holds even for structs! – a copy is created –There is no further connection between the argument and the parameter value in the function But they can point to the same thing, of course But: if the argument is an array name, the function parameter is initialized with a pointer to the array argument instead of a copy of the entire array –Implicit array promotion (we already knew this) 5

struct parameters A struct argument is copied (call-by-value) It is far more common to use a pointer to a struct as an argument instead of copying an entire struct –Gives same semantics as Java object references –Usually what you want – pointer to data that lives outside the function Also avoids cost of copying a possibly large object –But occasionally you want call-by value (small things like complex numbers, geometric points, …) Puzzle: if an argument is an array containing a single struct, is it copied or is it promoted to a pointer? –What if it’s a struct containing only a single array? 6

Linked lists, trees, and friends Very, very common data structures Building them in C –Use malloc to create nodes –Need to use casts for “generic” types –Memory management issues if shared nodes –Usually need to explicitly free entire thing when done –Shows tradeoffs between lists and arrays Look at the sample code and understand what it does/how it does it 7

C types There are an infinite number of types in C, but only a few ways to make them: –char, int, double, etc. (many variations like unsigned int, long, short, …; mostly “implementation-defined”) –void (placeholder; a “type” no expression can have) –struct T where there is already a declaration for that struct type –Array types (basically only for stack arrays and struct fields, every use is automatically converted to a pointer type) –T* where T is a type –union T, enum E (later, maybe) –function-pointer types (later) –typedefs (just expand to their definition; type synonym) 8

Typedef Defines a synonym for a type – does not declare a new type Syntax typedef type name; After this declaration, writing name is the same as writing type Caution: array typedef syntax is weirder Examples: typedef int int32; // use int32 for portability typedef struct point {// type tag optional (sortof) int32 x, y; } Point2d;// Point2d is synonym for struct typedef Point2d * ptptr;// pointer to Point2D Point2d p;// var declaration ptptr ptlist;// declares pointer 9

Casts, part 1 Syntax: (t)e where t is a type and e is an expression (same as Java) Semantics: It depends –If e is a numeric type and t is a numeric type, this is a conversion To wider type, get same value To narrower type, may not (will get mod) From floating-point to integral, will round (may overflow) From integral to floating-point, may round (but int to double is exact on most machines) Note: Java is the same without the “most machines” part Note: Lots of implicit conversions such as in function calls Bottom Line: Conversions involve actual operations; (double)3 is a very different bit pattern than (int)3 10

Casts, part 2 If e has type t1*, then (t2*)e is a (pointer) cast. –You still have the same pointer (index into the address space). –Nothing “happens” at run-time. –You are just “getting around” the type system, making it easy to write any bits anywhere you want. –Old example: malloc has return type void* void evil(int **p, int x) { int * q = (int*)p; *q = x; } void f(int **p) { evil(p,345); **p = 17; // writes 17 to address 345 (HYCSBWK) } Note: The C standard is more picky than we suggest, but few people know that and little code obeys the official rules. 11

C pointer casts, continued Questions worth answering: How does this compare to Java’s casts? –Unsafe, unchecked (no “type fields” in objects) –Otherwise more similar than it seems When should you use pointer casts in C? –For “generic” libraries ( malloc, linked lists, operations on arbitrary (generic) pointers, etc.) –For “subtyping” (later) What about other casts? –Casts to/from struct types (not struct pointer casts) are compile-time errors. 12