1 Structured Data Types A structure can be used to combine data of different types into a single (compound) data value. Like all data types, structures.

Slides:



Advertisements
Similar presentations
StructuresStructures Systems Programming. Systems Programming: Structures 2 Systems Programming: 2 StructuresStructures Structures Structures Typedef.
Advertisements

Programming in C Chapter 10 Structures and Unions
C Language.
Structures Spring 2013Programming and Data Structure1.
Structs CSE 2451 Rong Shi. Structures Structure – one or more values, called members, with possibly dissimilar types that are stored together – Group.
Structures. An array allows us to store a collection of variables However, the variables must be of the same type to be stored in an array E.g. if we.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Arrays in CCS-2301, B-Term Arrays in C (including a brief introduction to pointers) CS-2301, System Programming for Non-Majors (Slides include materials.
1 CSE 303 Lecture 12 structured data reading: Programming in C Ch. 9 slides created by Marty Stepp
1 Homework Turn in HW2 at start of next class. Starting Chapter 2 K&R. Read ahead. HW3 is on line. –Due: class 9, but a lot to do! –You may want to get.
Arrays in CCS-2301 B-term Arrays in C (with a brief Introduction to Pointers) CS-2301, System Programming for Non-majors (Slides include materials.
Pointers Applications
1 Structures. 2 C gives you several ways to create a custom data type. –The structure, which is a grouping of variables under one name and is called an.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
1 Using Classes Object-Oriented Programming Using C++ Second Edition 5.
Using Classes Object-Oriented Programming Using C++ Second Edition 5.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
8. Structures, File I/O, Recursion 18 th October IIT Kanpur 1C Course, Programming club, Fall 2008.
Structs. Structures We already know that arrays are many variables of the same type grouped together under the same name. Structures are like arrays except.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction Structures are somewhat like an array in that.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
Functions, Pointers, Structures Keerthi Nelaturu.
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.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
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.
Structured data types An elegant way to deal with the rgb image is to employ structured data types. A Java class is a generalization of a C struct. A structure.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. C H A P T E R F I V E Memory Management.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Sadegh Aliakbary Sharif University of Technology Spring 2011.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
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.
CS 31 Discussion, Week 8 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:00-1:00pm.
Implementing Subprograms What actions must take place when subprograms are called and when they terminate? –calling a subprogram has several associated.
Spring 2005, Gülcihan Özdemir Dağ Lecture 11, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 11 Outline 11.1.
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.
RUN-Time Organization Compiler phase— Before writing a code generator, we must decide how to marshal the resources of the target machine (instructions,
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
 Structures are like arrays except that they allow many variables of different types grouped together under the same name. For example you can create.
Lecture 15: Projects Using Similar Data. What is an Array? An array is a data structure consisting of related data items of the same type. Stored in a.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
1 C Language Structures. 2 Topics Concept of a structure Concept of a structure Structures in c Structures in c Structure declaration Structure declaration.
1 Structs. 2 Defining a Structure Often need to keep track of several pieces of information about a given thing. Example: Box We know its length width.
Review 1 List Data Structure List operations List Implementation Array Linked List.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 2 – August 23, 2001.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Structures and Union. Review bitwise operations –you need them for performance in terms of space and time –shifts are equivalent to arithmetics enumeration.
Advanced Pointer Topics. Pointers to Pointers u A pointer variable is a variable that takes some memory address as its value. Therefore, you can have.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
AP Java Ch. 4 Review Question 1  Java methods can return only primitive types (int, double, boolean, etc).
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.
CHAPTER 07 Arrays and Vectors (part II). OBJECTIVES In this part you will learn:  To pass arrays to functions.  Basic searching techniques.
Function PrototypetMyn1 Function Prototype We can declare a function before we use or define it by means of a function prototype. A function prototype.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Ex-1 #include <stdio.h> struct sample { int a=0; char b='A';
C Basics.
Structured Data Types A structure can be used to combine data of different types into a single (compound) data value. Like all data types, structures must.
Scope, Parameter Passing, Storage Specifiers
CS111 Computer Programming
Java Programming Language
Structures.
Structures, Unions, and Enumerations
Presentation transcript:

1 Structured Data Types A structure can be used to combine data of different types into a single (compound) data value. Like all data types, structures must be declared and defined. C has three different ways to define a structure – variable structures – tagged structures – type-defined structures

2 Structured Data Types A variable structure definition defines a struct variable. struct { unsigned char red; unsigned char green; unsigned char blue; } pixel; variable name DON’T FORGET THE SEMICOLON Members

3 Structured Data Types A tagged structure definition defines a type. We can use the tag to define variables, parameters, and return types. struct point_t structure tag { double x; Member names double y; }; DON’T FORGET THE SEMICOLON To Use: struct point_t point1, point2;

4 Structured Data Types Example 2 (tagged structure definition) struct pixel_t { unsigned char red; unsigned char green; unsigned char blue; }; DON’T FORGET THE SEMICOLON To Use: struct pixel_t pixel; Structure tag Members

5 Structured Data Types A typed-defined structure is the most powerful way to declare a structure. We can use the tag to define variables, parameters, and return types. typedef struct pixel_type { unsigned char red; unsigned char green; unsigned char blue; } pixel_t; To declare a variable of the new type, use: pixel_t pixel; New type name

6 Structured Data Types Example 2 (typed-defined structure) typedef struct pointType { double x; double y; } point_t; To declare variables of the type, use: point_t point1; point_t point2; These structure variable definitions create member variables x and y associated with the structure. New type name

Structured data types Member variables of a struct are accessed using the dot operator. pixel1.red = 200; pixel1.green = 200; pixel1.blue = 0; point1.x = 10.0; // type is double point1.y = 5.5; // type is double These variables may be used exactly like any other variables. 7

Example typedef struct student_type { int id; char grade; } student_t; int main( ) { student_t student; student.id = 2201; student.grade = ‘A’; fprintf(stdout, “id: %d, grade: %c\n”, student.id, student.grade); return 0; } 8

9 Initializing Structures At declaration time, members of a struct can be initialized in a manner similar to initializing array elements. pixel_t pixel = {255, 0, 100}; The sequence of values is used to initialize the successive variables in the struct. The order is essential. It is an error to have more initializers than variables. If there are fewer initializers than variables, the initializers provided are used to initialize the data members. The remainder are initialized to 0 for primitive types.

10 Use of sizeof() with structures The sizeof() operator should always be used in dynamic allocation of storage for structured data types and in reading and writing structured data types. However, it is somewhat easy to do this incorrectly.

11 Structures as parameters to functions A struct, like an int, may be passed to a function. The process works just like passing an int, in that: – The complete structure is copied to the stack – The function is unable to modify the caller's copy of the variable

12 Structures as parameters to functions #include typedef struct s_type { int a; double b; } sample_t; void funct(sample_t x) { fprintf(stdout, "x.a = %d\n", x.a); fprintf(stdout, "x.b= %lf\n", x.b); x.a = 1000; x.b = 55.5; } int main() { sample_t y; y.a = 99; y.b = 11.5; funct(y); fprintf(stdout, "y.a = %d\n", y.a); fprintf(stdout, "y.b = %lf\n", y.b); return 0; }

13 Structures as parameters to functions Sample Run: [11:26:47] rlowe:~ [142]./a.out x.a = 99 x.b= y.a = 99 y.b =

14 Structures as parameters to functions The disadvantages of passing structures by value are that copying large structures onto the stack – is very inefficient and – may even cause program failure due to stack overflow. typedef struct { int w[1024 * 1024]; } sample_t; /* passing a struct of type sampleType above will cause */ /* 4 Terabytes to be copied onto the stack. */ sample_t fourMB; for(i = 0; i < ; i++) { slow_call(fourMB); }

15 Passing the address of a struct A more efficient way is to pass the address of the struct. Passing an address requires that only a single word be pushed on the stack, regardless of how large the structure is. Furthermore, the called function can then modify the structure.

16 Passing the address of a struct #include typedef struct { int a; double b; } sample_t; /* Use the * operator. funct modifies the struct */ void funct (sample_t *x) { fprintf(stdout, "x->a = %d\n", x->a); // note the use of -> operator fprintf(stdout, "x->b = %lf\n", x->b); x->a = 1000; x->b = 55.5; } int main() { sample_t y; y.a = 99; y.b = 11.5; /* use the address operator, &, in the call */ funct(&y); fprintf(stdout, "y.a = %d\n", y.a); fprintf(stdout, "y.b = %lf\n", y.b); return 0; }

17 Passing the address of a struct Sample run: [11:39:29] rlowe:~ [169]./a.out x->a = 99 x->b = y.a = 1000 y.b =

18 Passing the address of a struct What if you do not want the recipient to be able to modify the structure? In the prototype and function header, use the * operator. – Use the const modifier void funct(const sample_t *x) ;

19 Using the const modifier #include typedef struct s_type { int a; double b; } sample_t; void funct(const sample_t *x) { fprintf(stdout, "x.a = %d\n", x->a); fprintf(stdout, "x.b = %d\n", x->a); x->a = 1000; x->b = 55.5; } int main( ) { sample_t y; y.a = 99; y.b = 11.5; /* to pass the address use the & operator */ funct(&y); fprintf(stdout, "y.a = %d\n", y.a); fprintf(stdout, "y.b = %d\n", y.b); return 0; } – The above code will generate a compile-time error.

20 Using the const modifier [11:34:04] rlowe:~ [147] gcc struc5.c struc5.c: In function 'funct': struc5.c:12: error: assignment of read-only location struc5.c:13: error: assignment of read-only location

21 Arrays within structures An element of a structure may be an array typedef struct { char name[25]; double payRate; int hoursWorked[7]; } timeCard_type; timeCard_type myTime; Elements of the array are accessed in the usual way: myTime.hoursWorked[5] = 6;

22 Arrays of structures We can also create an array of structure types: pixel_t pixelMap[400 * 300]; student_t roster[125]; To access an individual element of the array, pixelMap[20].red = 250; roster[50].gpa = 3.75;

23 Arrays of structures containing arrays We can also create an array of structures that contain arrays timeCard_type employees[50]; To access an individual element employees[10].hoursWorked[3] = 10;

24 Structures containing structures It is common for structures to contain elements which are themselves structures or arrays of structures. In these cases, the structure definitions should apear in "inside-out" order. This is done to comply with te usual rule of not referencing a name before it is defined.

25 Structures containing structures typedef struct { unsigned char red; unsigned char green; unsigned char blue; } pixel_t; typedef struct { int numRows; int numCols; pixel_t pixelData[400 * 300]; } image_t;

26 Structures as return values from functions Scalar values (int, float, etc) are efficiently returned in CPU registers. Historically, the structure assignments and the return of structures was not supported in C. But, the return of pointers (addresses), including pointers to structures, has always been supported.

27 Structures as return values from functions typedef struct { int a; double b; } sampleType; sample_t *funct ( ) { sample_t s; s->a = 1000; s->b = 55.5; return (&s); } int main() { sample_t *y; y = funct( ); fprintf(stdout, "y->a = %d\n", y->a); return 0; } [160]./a.out returnParam.c: In function 'funct': returnParam.c:8: warning: function returns address of local variable

28 Structures as return values from functions The reason for the warning is that the function is returning a pointer to a variable that was allocated on the stack during execution of the function. Such variables are subject to being wiped out by subsequent function calls.

29 Structures as return values from functions It is possible for a function to return a structure. This facility depends upon the structure assignment mechanisms which copies one complete structure to another. – This avoids the unsafe condition associated with returning a pointer, but – incurs the possibly extreme penalty of copying a very large structure

30 Structures as return values from functions #include typedef struct s_type { int a; double b; } sample_t; sample_t funct ( ) { sample_t s; s.a = 1000; s.b = 55.5; return s; } int main() { sample_t y; sample_t z; y = funct(); z = y; printf("%d %d\n", y.a, z.a); return 0; } [11:51:51] [184]./a.out 1000

31 Summary Passing/returning instances of structures potentially incurs big overhead. Passing/returning addresses incurs almost no overhead Accidental modifications can be prevented with const – Therefore, it is recommended that, in general, you never pass nor return an instance of a structure unless you have a very good reason for doing so. This problem does not arise with arrays. – The only way to pass an array by value in the C language is to embed it in a structure – The only way to return an array is to embed it in a structure.