Structures.

Slides:



Advertisements
Similar presentations
C Structures What is a structure? A structure is a collection of related variables. It may contain variables of many different data types---in contrast.
Advertisements

C Programming Lecture 23 Enumeration Types Structures.
Programming in C Chapter 10 Structures and Unions
1 Structures. 2 User-Defined Types C provides facilities to define one’s own types. These may be a composite of basic types ( int, double, etc) and other.
Chapter 6 Structures By C. Shing ITEC Dept Radford University.
Programming Languages and Paradigms The C Programming Language.
Review for Final Exam Dilshad M. NYU. In this review Arrays Pointers Structures Java - some basic information.
Structures A structure is a collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling.
Chapter 7: User-Defined Functions II
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures.
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.
Linked Lists Chained nodes of information create what are called linked lists, with each node providing a link to the next node. A useful feature of linked.
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.
Pointers| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2006 Slide 1 Pointers by Jumail Bin Taliba Faculty of Computer.
LECTURE 4: INFORMATION REPRESENTATION (PART II) COMP26120: ALGORITHMS AND IMPERATIVE PROGRAMMING.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Custom Templatized Data Structures.
DCT1063 Programming 2 CHAPTER 5 ADVANCED DATA TYPE (part 1) Mohd Nazri Bin Ibrahim Faculty of Computer Media and Technology TATi University College
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Learners Support Publications Classes and Objects.
Linked List Chapter Data Abstraction separates the logical properties of a data type from its implementation LOGICAL PROPERTIES – What are the.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 13: Data structures in C.
APS105 Lists. Structures Arrays allow a collection of elements –All of the same type How to collect elements of different types? –Structures; in C: struct.
+ Structures and Unions. + Introduction We have seen that arrays can be used to represent a group of data items that belong to the same type, such as.
CPS120: Introduction to Computer Science Lecture 15A Structures.
CPS120: Introduction to Computer Science Data Structures.
CPS120: Introduction to Computer Science Lecture 16 Data Structures, OOP & Advanced Strings.
Pointers PART - 2. Pointers Pointers are variables that contain memory addresses as their values. A variable name directly references a value. A pointer.
STRUCTURES. INTRODUCTION A structure is same as that of records. It stores related information about an entity. Structure is basically a user defined.
 Data Type is a basic classification which identifies different types of data.  Data Types helps in: › Determining the possible values of a variable.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Topic 5 Addresses, Pointers and Arrays. 2 Objectives (Textbook Chapter 14) You should be able to describe: Addresses and Pointers Pointer Operators Pointer.
Overview Working directly with memory locations is beneficial. In C, pointers allow you to: change values passed as arguments to functions work directly.
Object Lifetime and Pointers
Lesson #8 Structures Linked Lists Command Line Arguments.
Programming with ANSI C ++
Chapter 12 – Data Structures
5.13 Recursion Recursive functions Functions that call themselves
Lectures linked lists Chapter 6 of textbook
Linked Lists Chapter 6 Section 6.4 – 6.6
CS1010 Programming Methodology
Chapter 10-1: Structure.
Chapter 10: Pointers Starting Out with C++ Early Objects
UNIT-3 LINKED LIST.
TMF1414 Introduction to Programming
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.
CSCE 210 Data Structures and Algorithms
Programming Languages and Paradigms
Lecture 6 C++ Programming
Chapter 10: Pointers Starting Out with C++ Early Objects
Templates.
LINKED LISTS CSCD Linked Lists.
DATA HANDLING.
Pointers and References
14th September IIT Kanpur
Lecture 9 Structure 1. Concepts of structure Pointers of structures
C Structures, Unions, Bit Manipulations and Enumerations
Pointers, Dynamic Data, and Reference Types
EECE.2160 ECE Application Programming
Dr. Bhargavi Dept of CS CHRIST
COMP26120: Algorithms and Imperative programming
Classes and Objects.
Data Structures and Programming Techniques
Linked List.
Structures CSE 2031 Fall February 2019.
Submitted By : Veenu Saini Lecturer (IT)
Structures CSE 2031 Fall May 2019.
C Language B. DHIVYA 17PCA140 II MCA.
Pointers, Dynamic Data, and Reference Types
Week 9 - Monday CS222.
Presentation transcript:

Structures

Derived Data Type 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 aggregate data type. The “typedef” keyword, allow us to define a new user-defined type.

different types in one structure. A structure is a collection of variables referenced under one name, providing a convenient means of keeping related information together. It allows us to organize related data of different types in one structure.

Structure Declaration A structure declaration forms a template that can be used to create structure objects (instances of a structure). The variables that make up the structure are called members. Usually, the members of a structure are logically related.

General Form struct tag {     type member-name;     type member-name;     type member-name;     .     .     . } structure-variable(s);

keyword structure tag name struct addr {   char  name[30];   char  street[40];   char  city[20];   char  state[3];   unsigned long int zip; }; Terminated by a semicolon No variable has actually been created.

Structure Variable Declaration struct addr  addr_info; declares a variable of type struct addr called addr_info. The compiler automatically allocates sufficient memory to accommodate all of its members.

Memory allocated for addr_info Name 30 bytes Street 40 bytes City 20 bytes State 3 bytes Zip 4 bytes

You can declare one or more objects when declare a struct type struct addr {   char name[30];   char street[40];   char city[20];   char state[3];   unsigned long int zip; } addr_info, binfo, cinfo;

Initialization of Structures All, Extern and Static Variables including structure variables that are not explicitly initialized, are automatically initialized to 0 (appropriate value for that member’s type)

Accessing Structure Members Individual members of a structure are accessed through the use of the Dot Operator (“.”). General form: object-name.member-name

See slide 9: Created 3 Struct vars. e.g., addr_info.zip = 12345; printf("%lu", addr_info.zip); gets(addr_info.name); for(t=0; addr_info.name[t]; ++t)   putchar( addr_info.name[t] );

Structure Assignments #include <stdio.h> int main(void) {   struct {     int a;     int b;   } x, y;   x.a = 10; y = x;  /* assign one structure to another */   printf("%d", y.a);   return 0; } Do not need to assign the value of each member separately

Array of Structs WHY? What does an array of structs allow us to do that is not possible with any other single structure?

Arrays of Structures To declare an array of structures, you must first define a structure and then declare an array variable of that type. struct addr  addr_list[100]; printf("%lu", addr_list[2].zip); addr_list[2].name[0] = 'X';

Passing Structures to Functions Passing Structure Members to Functions. Passing Entire Structures to Functions

Passing Structure Members to Functions When you pass a member of a structure to a function, you are passing the value of that member to the function. It is irrelevant that the value is obtained from a member of a structure. struct friend { char  x;    int y;    float  z;    char  s[10]; } mike;

func(mike. x); /. passes character value of x. / func2(mike. y); / func(mike.x);      /* passes character value of x  */ func2(mike.y);    /* passes integer value of y  */ func3(mike.z);    /* passes float value of z  */ func4(mike.s);    /* passes address of string s  */ func( mike.s[2] ] ); /* passes character value of s[2]  */ func(&mike.x); /* passes address of character x */ func2(&mike.y); /* passes address of integer y */ func3(&mike.z); /* passes address of float z */ func4(mike.s); /* passes address of string s */ func(&mike.s[2]);/* passes address of character s[2] */

Passing Entire Structures to Functions Call-by-value: #include <stdio.h>   struct Example_type {   int a, b;   char ch; } ;

struct_type must match void f1(struct Example_type  parm); int main(void) {   struct Example_type arg;   arg.a = 1000;   f1(arg);   return 0; } void f1(struct Example_type  parm) {   printf(''%d", parm.a); } struct_type must match

In Header File: cl_info.h #define CLASS_SIZE 100 struct student { char *last_name; int student_id; char grade; }; In Program File : #include “cl_info.h” MAIN( ) { struct student temp, class [CLASS_SIZE]; ….. } e.g.: To count the number of failing students in a given Class.

Structure Pointers When a pointer to a structure is passed to a function, only the address of the structure is pushed on the stack. This makes for very fast function calls. Passing a pointer makes it possible for the function to modify the contents of the structure used as the argument via call-by-reference.

Declaring a Structure Pointer Like other pointers, structure pointers are declared by placing * in front of a structure variable's name. struct addr  *addr_pointer;

Using Structure Pointers To pass a structure to a function using call by reference. To create linked lists and other dynamic data structures that rely on dynamic allocation.

struct bal {   float balance;   char name[80]; } person; struct bal *p;  /* decl a structure pointer */ p = &person;

The Structure Pointer Operator –> Used to access the members of a structure via a pointer. p–>balance Forms: (*pointer-To-Struct). member or pointer-To-Struct -> member

struct student temp, *p = &temp; temp.grade = ‘A’; temp.last_name = “Bushker”; temp.student_id = 590017; struct student { char *last_name; int student_id; char grade; };

Expression Equivalent Value temp.grade p –> grade A temp.last_name p –> last_name Bushker temp.student_id p –> student_id 590017 (*p).student_id 590017 Parenthesis are necessary (dot) has higher priority than *

Arrays and Structures Within Structures A member of a structure can be either a single variable or an aggregate type. In C aggregate types are arrays and structures.

Arrays Within Structures struct x {   int a[10] [10]; /* 10 x 10 array of ints */   float b; } y; To reference element [ 3,7] in member a of Structure y. y.a[3][7]

Structures within Structures worker.address.zip = 93456; The C89 standard specifies that structures can be nested to at least 15 levels. struct emp {   struct addr address; /* nested structure */   float wage; } worker;

Using sizeof to Ensure Portability struct s {   char ch;   int i;   double f; } s_var; Type Size in Bytes char 1 int 4 double 8 sizeof(s_var) is 13 (8+4+1). struct s *p; p = malloc(sizeof(struct s));

typedef You can define new data type names by using the keyword typedef You are not actually creating a new data type. You define a new name for an existing type. The primary advantage of the type definition is that it allows you to replace a complex name, such as a pointer declaration, with a mnemonic that makes the program easier to read and follow.

General Form: typedef type newname; typedef  float  BALANCE; BALANCE   over_due;

E.g., The declaration for an array of pointers to strings. Char * stringPtrAry[20]; Typedef char * STRING; STRING StrPtrAry[20];

Typedef with Structures typedef struct { char id[10]; char name[26]; int gradepts; } STUDENT; A typename not a variable. STUDENT pupil; void printstudent (STUDENT Stu);

LINKED LIST DATA STRUCTURE A Linked List is an ordered collection of data in which each element contains 2 parts: data and link. The data part holds info fields and the link is used to chain the data together. It contains a pointer that identifies the in next node the list. A Pointer variable points to the first node (HEAD) in the list. Memory for each node is allocated dynamically.

The Head ptr gives acess to the LINKED LIST which is a sequence of linked nodes. Data Data Data Data Head

Self-Referential Structures The node in a linked list are called self-referential structures: Each instance of the structure contains a pointer member to another instance of the same type. This gives us the ability to create our linked list structure in which one instance of a node structure points to another instance of the node structure.

Type Definition for a Linked List typedef struct { int mem1; double mem2: /* other data fields */ } DATA; typedef struct nodetag { DATA data; struct nodetag *link; } NODE; A TYPE for EACH NODE

Pointers to Linked Lists One of the attributes of a linked list is that its data are NOT stored with physical adjaceny- like array data is. We need to identify the first logical node in the list which we do with a pointer variable designated as the HEAD POINTER. A linked list MUST always have a head ptr and will likely have other pointers which will be used for implementing LL activities (e.g., insertions, deletions, searches …).

Primitive List Functions To work with a linked list we need some basic operations that manipulate the nodes. INSERT a Node: At the beginning. At the end. Anywhere in the list. DELETE a Node: At the beginning. Anywhere it is. SEARCH for a Find the location for node. above activities.

Inserting a New Node Steps to insert a new node: 1. Allocate memory for the new node. 2. Determine the insertion point. Implies a search function. We need to know the new nodes logical predecessor. 3. Point the new node to its successor. 4. Point the predecessor to the new node.