Reading Assignment KN King Chapter 16, 18 Structures and Unions

Total Page:16

File Type:pdf, Size:1020Kb

Reading Assignment KN King Chapter 16, 18 Structures and Unions Reading Assignment Structures and Unions A structure is a mechanism that allows several data items of arbitrary types to be treated as a single entity. K.N. King Chapter 16, 18 Structures are typically used when some block of logically related informantion needs to be processed in a program. Examples: name, address, telephone number X coordinate, Y coordinate, Z coordinate student name, student number, assignment marks A union is a mechanism for saving space when several mutually exclusive data items need to be stored. Good Style: always use a typedef to create a single point of definition for any structure or union that has a significant use in a program. 216 217 Structure Declaration Structure Declaration Examples struct structureTag ¢ /* Type declarations */ structureFields struct A B ¢ identifierList ; £ int B , C ; D double X , Y ; X A The structureTag provides a name for the structure. This name can be used char C ; Y like a type name to declare variables of the structure type. struct A * nextA ; C ; nextA The optional identifierList is a list of structure variables that are being £ declared at the same time as the structure. typedef struct AmyA; The structureFields are ordinary data declarations that describe data /* Variable declarations */ contained in the structure. struct AS1, S2 ; S1 Example: struct exStruct typedef struct ¤ ¤ struct ¢ char name[ 25 ] ; char label[ 33 ] ; int J , K ; S2 int price float value J ; ; S3 ; S3 K £ computer1, computer2 ; myStruct ; ¥ ¥ myA S4 ; S4 struct exStruct computer3 ; myStruct s1, s2 ; 218 219 HOW TO Use Structures To access a field in a structure variable, use the field access operator . computer1.price = 2199 ; Each structure body represents a new scope. Declare the variables that you want to treat as a unit in this scope. If P is a pointer variable that has been declared as a pointer to some structure type S, then (assuming P points at a structure) the fields of the structure can Structure variables can be initialized with declaration by giving a list of values be accessed using the pointer operator -> for the structure fields. struct compStruct compPtr = & computer2 ; struct compStruct ¢ compPtr -> price = 3799 ; char name[ NAME LEN+1]; int price; the fields in a structure can be any C type-name including arrays and computer1 = ”IBM”, 3499 , computer2 = ”Dell”, 2265 ; structures. If a structure has a structure tag, a pointer to the structure can be £ ¢ £ ¢ £ declared inside the structure. The assignment operator applies to entire structures. The contents of the structure on the right side of the = is copied to the The size of a structure is approximately the sum of the sizes of the fields in structure on the left side. the structure. Use sizeof to get the exact size of any structure. computer2 = computer1 ; Entire structures can not be compared. 220 221 HOW TO Use Structures Union Types The primary use of structures is to package several related variables together so that they can be treated as a single object. union unionTag ¢ fieldAlternativesList Structures can be used as function arguments anda function can return a identifierList ; structure as its value. £ WARNING: Structures are copied when they are passed by value or returned. Excessive copying of large structures can make a program inefficient. unionTag is the name of the union type Consider using a pointer to the structure instead. The fieldAlternativesList is a list of mutually exclusive fieldAlternatives. Any type of object can be used as a field of a structure including another Each fieldAlternatives is a single data declaration. structure. Use a structure to pack several data items into one alternative. Examples: struct A struct B ¤ ¤ float X , Y ; struct ABownA; The optional identifierList is a list of union variables that are being declared at the same time as the union. int K ; int K ; ; myA Array[ 10 ] ; ¥ typedef struct AmyA; ; ¥ 222 223 Union Declaration Examples /* Type declarations */ /* Type declarations */ HOW TO Use Unions union A union typeOverlay ¢ ¢ Unions are a mechanism for saving space when several mutually exclusive int B , C ; int integer ; alternative sets of data need to be stored and treated like a single object. double X , Y ; float floater ; The fieldAlternatives overlap in memory so only one is active at any instant in char C ; unsigned char bytes[ 4 ] ; time. struct A * nextA ; void * pointer ; ; ; The size of a union is approximately the size of the largest field alternative in £ £ typedef union AmyUA; the union. Use sizeof to get the exact size of a union. C does NO run-time checking for proper use of unions The programmer must provide some way of indicating which field alternative is active at any instant in time 224 225 Example of a self-identifying structure/union. Reading Assignment typedef enum point , square , circle , triangle ¤ ¥ uType ; struct uStruct ¤ uKind K.N. King Sections 17.1, 17.3, 17.4 uType unionKind ; side union value ¤ radius sideA sideB sideC double side ; /* square */ int radius /* circle */ ; Xcoordinate float sideA , sideB , sideC ; /* triangle */ value ; ¥ Ycoordinate double Xcoordinate , Ycoodinate ; ; ¥ 226 227 Dynamic Storage Allocation Dynamic Storage Allocation Dynamic storage allocation is a mechanism that allows the programmer to Storage can be allocated for any type of data (i.e any type-name ). create new storage for data during the execution of a program Pointers are used to access dynamically allocated storage. Dynamic storage allocation is used to build complicated data structures like Storage must be allocated and deallocated under programmer control lists, trees, and graphs whose size and shape is determined during program execution Items in storage can be linked together with pointers in arbitrary ways Items are accessed using pointers, any item not pointed to by some pointer is Think of using dynamic storage allocation for problems where you have to deal with arbitrarily large amounts of data or where the structure of the data permanently inaccessible isn’t known before program execution Use of dynamic storage allocation is an important programming technique because it frees the programmer from the restrictions imposed by statically sized data structures. 228 229 Storage Allocation Functions malloc doesn’t initialize memory but calloc does initializes the memory by setting all bits to 0. #include ¦ stdlib.h § void *malloc( size tsize) When it is not possible to locate a block of memory large enough, the storage void *calloc( size t nobj , size tsize) allocation functions return NULL. void *realloc( void *p,size tsize) WARNING: Always check if the return value is NULL. p = (char *) malloc(n+1); if (p == NULL) ... malloc allocates size bytes of storage and returns a pointer to the storage. calloc allocates storage for an array of nobj elements where each element WARNING: Be sure that a pointer passed to realloc came from previous call requires size bytes of storage of malloc, calloc, or realloc realloc changes (smaller or larger) the size of the block of storage pointed to WARNING: realloc may move the data being reallocated to a different part of by p to be size bytes. Returns a pointer to the new storage. Copies old block memory. This will invalidate all existing pointers to that data. The ONLY of storage to new block of storage up to min( oldSize, newSize) pointer you can trust is the one returned by malloc. Since malloc et.al. return a value of type void * you should use a type cast to Good Technique: Use the sizeof operator to get the correct size for the convert the type of the pointer returned to what you need. storage that you are allocating. 230 231 Deallocating Storage HOW TO Use Storage Allocation void free( void *p) Always use sizeof to calculate the amount of storage reqested from the storage allocation functions. It is the only way to always get the correct size. Never pass any pointer to free that wasn’t obtained directly from one of the free releases the storage block pointed to by p. storage allocation functions. CHAOS will ensue if you get this wrong. That storage must have been allocated using malloc, calloc or realloc or Safe Storage Allocation CHAOS will ensue. #define MALLOC( size, type , pointer ) \ Dangling pointers are pointers that point to storage elements that have void * mTemp ; \ ¢ already been freed mTemp = malloc( (size) ) ; \ assert (mTemp!= NULL ) ; \ It is a logic error in your program if you try to use a dangling pointer pointer = ( type ) mTemp ; \ £ Example double * Dptr ; MALLOC( 250 *sizeof( double ),double * ,Dptr) 232 233 Storage Allocation Examples NULL Pointer Dereferencing int * A ; int nWords = 100 ; It is an ERROR to apply the pointer dereferencing operator ( * ) to any pointer that has the value NULL. A=(int * ) malloc(nWords * sizeof ( int )); The following property should hold for correct programs. At every point where a pointer variable is dereferenced, the pointer typedef struct ¢ variable does not have the value NULL int X , Y ; If you cannot make an informal argument that this property holds at every Point ; £ pointer dereference than you have an ERROR in your program. typedef struct Point * PointPtr ; WARNING: The NULL pointer is lurking everywhere waiting to cause #define PointArraySize ( 360 ) your program to crash PointPtr P ; P = ( PointPtr ) calloc( PointArraySize , sizeof ( Point ) ) ; P[100] -> X=10; P[100] -> Y=20; 234 235 Dangling Pointer Example Dangling Pointers typedef struct ¢ A dangling pointer is a pointer that points at some block of storage that has float X ; been freed. ... It is an ERROR to use a dangling pointer since it points to GARBAGE. The bigStruct ; following property should hold for correct programs. £ typedef struct bigStruct * bigPtr ; At every point where a pointer variable is dereferenced, the pointer bigPtr P, Q ; variable can not be a dangling pointer. P = ( bigPtr ) malloc( sizeof ( bigStruct ) ) ; If you cannot make an informal argument that this property holds at every pointer dereference than you have an ERROR in your program.
Recommended publications
  • Create Union Variables Difference Between Unions and Structures
    Union is a user-defined data type similar to a structure in C programming. How to define a union? We use union keyword to define unions. Here's an example: union car { char name[50]; int price; }; The above code defines a user define data type union car. Create union variables When a union is defined, it creates a user-define type. However, no memory is allocated. To allocate memory for a given union type and work with it, we need to create variables. Here's how we create union variables: union car { char name[50]; int price; } car1, car2, *car3; In both cases, union variables car1, car2, and a union pointer car3 of union car type are created. How to access members of a union? We use . to access normal variables of a union. To access pointer variables, we use ->operator. In the above example, price for car1 can be accessed using car1.price price for car3 can be accessed using car3->price Difference between unions and structures Let's take an example to demonstrate the difference between unions and structures: #include <stdio.h> union unionJob { //defining a union char name[32]; float salary; int workerNo; } uJob; struct structJob { char name[32]; float salary; int workerNo; } sJob; main() { printf("size of union = %d bytes", sizeof(uJob)); printf("\nsize of structure = %d bytes", sizeof(sJob)); } Output size of union = 32 size of structure = 40 Why this difference in size of union and structure variables? The size of structure variable is 40 bytes. It's because: size of name[32] is 32 bytes size of salary is 4 bytes size of workerNo is 4 bytes However, the size of union variable is 32 bytes.
    [Show full text]
  • [Note] C/C++ Compiler Package for RX Family (No.55-58)
    RENESAS TOOL NEWS [Note] R20TS0649EJ0100 Rev.1.00 C/C++ Compiler Package for RX Family (No.55-58) Jan. 16, 2021 Overview When using the CC-RX Compiler package, note the following points. 1. Using rmpab, rmpaw, rmpal or memchr intrinsic functions (No.55) 2. Performing the tail call optimization (No.56) 3. Using the -ip_optimize option (No.57) 4. Using multi-dimensional array (No.58) Note: The number following the note is an identification number for the note. 1. Using rmpab, rmpaw, rmpal or memchr intrinsic functions (No.55) 1.1 Applicable products CC-RX V2.00.00 to V3.02.00 1.2 Details The execution result of a program including the intrinsic function rmpab, rmpaw, rmpal, or the standard library function memchr may not be as intended. 1.3 Conditions This problem may arise if all of the conditions from (1) to (3) are met. (1) One of the following calls is made: (1-1) rmpab or __rmpab is called. (1-2) rmpaw or __rmpaw is called. (1-3) rmpal or __rmpal is called. (1-4) memchr is called. (2) One of (1-1) to (1-3) is met, and neither -optimize=0 nor -noschedule option is specified. (1-4) is met, and both -size and -avoid_cross_boundary_prefetch (Note 1) options are specified. (3) Memory area that overlaps with the memory area (Note2) read by processing (1) is written in a single function. (This includes a case where called function processing is moved into the caller function by inline expansion.) Note 1: This is an option added in V2.07.00.
    [Show full text]
  • Data Structures, Buffers, and Interprocess Communication
    Data Structures, Buffers, and Interprocess Communication We’ve looked at several examples of interprocess communication involving the transfer of data from one process to another process. We know of three mechanisms that can be used for this transfer: - Files - Shared Memory - Message Passing The act of transferring data involves one process writing or sending a buffer, and another reading or receiving a buffer. Most of you seem to be getting the basic idea of sending and receiving data for IPC… it’s a lot like reading and writing to a file or stdin and stdout. What seems to be a little confusing though is HOW that data gets copied to a buffer for transmission, and HOW data gets copied out of a buffer after transmission. First… let’s look at a piece of data. typedef struct { char ticker[TICKER_SIZE]; double price; } item; . item next; . The data we want to focus on is “next”. “next” is an object of type “item”. “next” occupies memory in the process. What we’d like to do is send “next” from processA to processB via some kind of IPC. IPC Using File Streams If we were going to use good old C++ filestreams as the IPC mechanism, our code would look something like this to write the file: // processA is the sender… ofstream out; out.open(“myipcfile”); item next; strcpy(next.ticker,”ABC”); next.price = 55; out << next.ticker << “ “ << next.price << endl; out.close(); Notice that we didn’t do this: out << next << endl; Why? Because the “<<” operator doesn’t know what to do with an object of type “item”.
    [Show full text]
  • Coredx DDS Type System
    CoreDX DDS Type System Designing and Using Data Types with X-Types and IDL 4 2017-01-23 Table of Contents 1Introduction........................................................................................................................1 1.1Overview....................................................................................................................2 2Type Definition..................................................................................................................2 2.1Primitive Types..........................................................................................................3 2.2Collection Types.........................................................................................................4 2.2.1Enumeration Types.............................................................................................4 2.2.1.1C Language Mapping.................................................................................5 2.2.1.2C++ Language Mapping.............................................................................6 2.2.1.3C# Language Mapping...............................................................................6 2.2.1.4Java Language Mapping.............................................................................6 2.2.2BitMask Types....................................................................................................7 2.2.2.1C Language Mapping.................................................................................8 2.2.2.2C++ Language Mapping.............................................................................8
    [Show full text]
  • Julia's Efficient Algorithm for Subtyping Unions and Covariant
    Julia’s Efficient Algorithm for Subtyping Unions and Covariant Tuples Benjamin Chung Northeastern University, Boston, MA, USA [email protected] Francesco Zappa Nardelli Inria of Paris, Paris, France [email protected] Jan Vitek Northeastern University, Boston, MA, USA Czech Technical University in Prague, Czech Republic [email protected] Abstract The Julia programming language supports multiple dispatch and provides a rich type annotation language to specify method applicability. When multiple methods are applicable for a given call, Julia relies on subtyping between method signatures to pick the correct method to invoke. Julia’s subtyping algorithm is surprisingly complex, and determining whether it is correct remains an open question. In this paper, we focus on one piece of this problem: the interaction between union types and covariant tuples. Previous work normalized unions inside tuples to disjunctive normal form. However, this strategy has two drawbacks: complex type signatures induce space explosion, and interference between normalization and other features of Julia’s type system. In this paper, we describe the algorithm that Julia uses to compute subtyping between tuples and unions – an algorithm that is immune to space explosion and plays well with other features of the language. We prove this algorithm correct and complete against a semantic-subtyping denotational model in Coq. 2012 ACM Subject Classification Theory of computation → Type theory Keywords and phrases Type systems, Subtyping, Union types Digital Object Identifier 10.4230/LIPIcs.ECOOP.2019.24 Category Pearl Supplement Material ECOOP 2019 Artifact Evaluation approved artifact available at https://dx.doi.org/10.4230/DARTS.5.2.8 Acknowledgements The authors thank Jiahao Chen for starting us down the path of understanding Julia, and Jeff Bezanson for coming up with Julia’s subtyping algorithm.
    [Show full text]
  • Bits, Bytes and Integers ‘
    Bits, Bytes and Integers ‘- Karthik Dantu Ethan Blanton Computer Science and Engineering University at Buffalo [email protected] 1 Karthik Dantu Administrivia • PA1 due this Friday – test early and often! We cannot help everyone on Friday! Don’t expect answers on Piazza into the night and early morning • Avoid using actual numbers (80, 24 etc.) – use macros! • Lab this week is on testing ‘- • Programming best practices • Lab Exam – four students have already failed class! Lab exams are EXAMS – no using the Internet, submitting solutions from dorm, home Please don’t give code/exam to friends – we will know! 2 Karthik Dantu Everything is Bits • Each bit is 0 or 1 • By encoding/interpreting sets of bits in various ways Computers determine what to do (instructions) … and represent and manipulate numbers, sets, strings, etc… • Why bits? Electronic Implementation‘- Easy to store with bistable elements Reliably transmitted on noisy and inaccurate wires 0 1 0 1.1V 0.9V 0.2V 0.0V 3 Karthik Dantu Memory as Bytes • To the computer, memory is just bytes • Computer doesn’t know data types • Modern processor can only manipulate: Integers (Maybe only single bits) Maybe floating point numbers ‘- … repeat ! • Everything else is in software 4 Karthik Dantu Reminder: Computer Architecture ‘- 5 Karthik Dantu Buses • Each bus has a width, which is literally the number of wires it has • Each wire transmits one bit per transfer • Each bus transfer is of that width, though some bits might be ignored • Therefore, memory has a word size from‘-the viewpoint of
    [Show full text]
  • Fixed-Size Integer Types Bit Manipulation Integer Types
    SISTEMI EMBEDDED AA 2012/2013 Fixed-size integer types Bit Manipulation Integer types • 2 basic integer types: char, int • and some type-specifiers: – sign: signed, unsigned – size: short, long • The actual size of an integer type depends on the compiler implementation – sizeof(type) returns the size (in number of bytes) used to represent the type argument – sizeof(char) ≤ sizeof(short) ≤ sizeof(int) ≤ sizeof(long)... ≤ sizeof(long long) Fixed-size integers (1) • In embedded system programming integer size is important – Controlling minimum and maximum values that can be stored in a variable – Increasing efficiency in memory utilization – Managing peripheral registers • To increase software portability, fixed-size integer types can be defined in a header file using the typedef keyword Fixed-size integers (2) • C99 update of the ISO C standard defines a set of standard names for signed and unsigned fixed-size integer types – 8-bit: int8_t, uint8_t – 16-bit: int16_t, uint16_t – 32-bit: int32_t, uint32_t – 64-bit: int64_t, uint64_t • These types are defined in the library header file stdint.h Fixed-size integers (3) • Altera HAL provides the header file alt_types.h with definition of fixed-size integer types: typedef signed char alt_8; typedef unsigned char alt_u8; typedef signed short alt_16; typedef unsigned short alt_u16; typedef signed long alt_32; typedef unsigned long alt_u32; typedef long long alt_64; typedef unsigned long long alt_u64; Logical operators • Integer data can be interpreted as logical values in conditions (if, while,
    [Show full text]
  • Advanced Programming Techniques (Amazing C++) Bartosz Mindur Applied Physics and Computer Science Summer School '20
    Advanced Programming Techniques (Amazing C++) Bartosz Mindur Applied Physics and Computer Science Summer School '20 Kraków, 2020-07-16 [1 / 37] www.menti.com/28f8u5o5xr Which programming language do you use the most? cpp h s a b python a c v a y j csharp l b m e s s a 18 [2 / 37] Agenda References C++ history C++11/14 - must be used C++17 - should be used C++20 - may (eventually) be used ... [3 / 37] www.menti.com/uaw75janh7 What is your current knowledge of C++? Core C++ 3.1 C++ STL ! e k e 2.2 i l n o d o N C++ 11/14 G 2.4 C++17 1.4 17 [4 / 37] References and tools [5 / 37] C++ links and cool stu C++ links Online tools ISO C++ Compiler Explorer cpp references cpp insights c & cpp programming cpp.sh #include <C++> repl.it LernCpp.com Quick Bench cplusplus.com Online GDB CppCon piaza.io CppCast codiva.io Bartek Filipek ... Oine tools CMake Valgrind GDB Docker Clang Static Analyzer [6 / 37] Things you (probably) already know well [7 / 37] C++ basics variables conversion and casts references implicit pointers explicit functions static statements dynamic loops exceptions declaration function templates initialization class templates operator overloading smart pointers classes basics of the STL constructors & destructor containers fields iterators methods algorithms inheritance building programs types compilation virtual functions linking polymorphism libraries multiple inheritance tools [8 / 37] www.menti.com/32rn4èy3j What is the most important C++ feature? polymorphism templates encapsulation s r e t n i e inheritance o c p n a s w hardware accessibility i e r e s g s n multithreading i a l generic programming c 8 [9 / 37] C++ history [10 / 37] The Design of C++ The Design of C++, a lecture by Bjarne Stroustrup This video has been recorded in March, 1994 [link] The Design of C++ , lecture by Bjarne Stroustr… Do obejrze… Udostępnij [11 / 37] C++ Timeline [link] [12 / 37] C++11/C++14 [13 / 37] Move semantics Value categories (simplied) Special members lvalue T::T(const T&& other) or T::T(T&& other) T& operator=(T&& other) e.g.
    [Show full text]
  • Type-Check Python Programs with a Union Type System
    日本ソフトウェア科学会第 37 回大会 (2020 年度) 講演論文集 Type-check Python Programs with a Union Type System Senxi Li Tetsuro Yamazaki Shigeru Chiba We propose that a simple type system and type inference can type most of the Python programs with an empirical study on real-world code. Static typing has been paid great attention in the Python language with its growing popularity. At the same time, what type system should be adopted by a static checker is quite a challenging task because of Python's dynamic nature. To exmine whether a simple type system and type inference can type most of the Python programs, we collected 806 Python repositories on GitHub and present a preliminary evaluation over the results. Our results reveal that most of the real-world Python programs can be typed by an existing, gradual union type system. We discovered that 82.4% of the ex- pressions can be well typed under certain assumptions and conditions. Besides, expressions of a union type are around 3%, which indicates that most of Python programs use simple, literal types. Such preliminary discovery progressively reveals that our proposal is fairly feasible. while the effectiveness of the type system has not 1 Introduction been empirically studied. Other works such as Py- Static typing has been paid great attention in type implement a strong type inferencer instead of the Python language with its growing popularity. enforcing type annotations. At the same time, what type system should be As a dynamically typed language, Python excels adopted by a static checker is quite a challenging at rapid prototyping and its avail of metaprogram- task because of Python's dynamic nature.
    [Show full text]
  • Malloc & Sizeof
    malloc & sizeof (pages 383-387 from Chapter 17) 1 Overview Whenever you declare a variable in C, you are effectively reserving one or more locations in the computerʼs memory to contain values that will be stored in that variable. The C compiler automatically allocates the correct amount of storage for the variable. In some cases, the size of the variable may not be known until run-time, such as in the case of where the user enters how many data items will be entered, or when data from a file of unknown size will be read in. The functions malloc and calloc allow the program to dynamically allocate memory as needed as the program is executing. 2 calloc and malloc The function calloc takes two arguments that specify the number of elements to be reserved, and the size of each element in bytes. The function returns a pointer to the beginning of the allocated storage area in memory, and the storage area is automatically set to 0. The function malloc works similarly, except that it takes only a single argument – the total number of bytes of storage to allocate, and also doesnʼt automatically set the storage area to 0. These functions are declared in the standard header file <stdlib.h>, which should be included in your program whenever you want to use these routines. 3 The sizeof Operator To determine the size of data elements to be reserved by calloc or malloc in a machine-independent way, the sizeof operator should be used. The sizeof operator returns the size of the specified item in bytes.
    [Show full text]
  • Software II: Principles of Programming Languages
    Software II: Principles of Programming Languages Lecture 6 – Data Types Some Basic Definitions • A data type defines a collection of data objects and a set of predefined operations on those objects • A descriptor is the collection of the attributes of a variable • An object represents an instance of a user- defined (abstract data) type • One design issue for all data types: What operations are defined and how are they specified? Primitive Data Types • Almost all programming languages provide a set of primitive data types • Primitive data types: Those not defined in terms of other data types • Some primitive data types are merely reflections of the hardware • Others require only a little non-hardware support for their implementation The Integer Data Type • Almost always an exact reflection of the hardware so the mapping is trivial • There may be as many as eight different integer types in a language • Java’s signed integer sizes: byte , short , int , long The Floating Point Data Type • Model real numbers, but only as approximations • Languages for scientific use support at least two floating-point types (e.g., float and double ; sometimes more • Usually exactly like the hardware, but not always • IEEE Floating-Point Standard 754 Complex Data Type • Some languages support a complex type, e.g., C99, Fortran, and Python • Each value consists of two floats, the real part and the imaginary part • Literal form real component – (in Fortran: (7, 3) imaginary – (in Python): (7 + 3j) component The Decimal Data Type • For business applications (money)
    [Show full text]
  • Mallocsample from Your SVN Repository
    DYNAMIC MEMORY ALLOCATION IN C CSSE 120—Rose Hulman Institute of Technology Final Exam Facts Date: Monday, May 24, 2010 Time: 6 p.m. to 10 p.m. Venue: O167 or O169 (your choice) Organization: A paper part and a computer part, similar to the first 2 exams. The paper part will emphasize both C and Python. You may bring two double-sided sheets of paper this time. There will be a portion in which we will ask you to compare and contrast C and Python language features and properties. The computer part will be in C. The computer part will be worth approximately 65% of the total. Q1-2 Sample Project for Today Check out 29-MallocSample from your SVN Repository Verify that it runs, get help if it doesn't Don’t worry about its code yet; we’ll examine it together soon. Memory Requirements Any variable requires a certain amount of memory. Primitives, such an int, double, and char, typically may require between 1 and 8 bytes, depending on the desired precision, architecture, and Operating System’s support. Complex variables such as structs, arrays, and strings typically require as many bytes as their components. How large is this? sizeof operator gives the number bytes needed to store a value typedef struct { sizeof(char) char* name; int year; sizeof(char*) double gpa; sizeof(int) } student; sizeof(float) sizeof(double) char* firstName; int terms; sizeof(student) double scores; sizeof(jose) student jose; printf("size of char is %d bytes.\n", sizeof(char)); Examine the beginning of main of 29-MallocSample.
    [Show full text]