SlideShare uma empresa Scribd logo
1 de 19
Structures

1
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 user-defined types.
• The most common user-defined type is a structure,
defined by the keyword struct.

2
Structures
• A structure is a collection of one or more variables,
possibly of different types, grouped together under a
single name
• Structures are user-defined aggregate types.
• They assist program organisation by
– Grouping logically related data, and giving this set of
variables a higher-level name and more abstract
representation.
– Reducing the number of parameters that need to be passed
between functions.
– Providing another means to return multiple values from a
function.
3
Structure Syntax
• A structure is defined by the keyword struct followed by a set of
variables enclosed in braces.
• Consider the following structure to represent a person’s details.
struct Personnel {
char name[100];
int age;
double height;
};

• The variables name, age and height are called members of the
structure type Personnel.

4
Declaring Structure Variables
•

There are two ways to define variables of a particular
structure type.
1. Declare them at the structure definition.
struct Personnel {
char name[100];
int age;
double height;
} p1, p2, p3; /* Define 3 variables */

2. Define the variables at some point after the structure
definition.
struct Personnel p1, p2, p3; /* Define 3 variables */
5
Initialising Structure Variables
•

A structure may be initialised when it is
defined using brace notation.
struct Personnel captain = {“Fred”, 37, 1.83};

•

The order of values in the initialise list
matches the order of declarations in the
structure.

6
Accessing Members
• Members of a structure type may be accessed via the
“.” member operator.
struct Personnel captain;

strcpy(captain.name, “Fred”);
captain.age = 37;
captain.height = 1.83;
printf(“%s is %d years old.”,
captain.name, captain.age);

7
Nested Structures
• Structures may be defined inside other
structures.
struct first
{
struct second
{
int a;
}s;
double amount;
}f;

• To access lower-level members, need to use
member operator multiple times.
f.s.a = 2.1;
f.amount = 75.4;
8
Operations on Structures
• Structure types only support one of the operations that are
permitted on primitive types.
– Assignment (ie., copying) is permitted
– All other operations (ie., arithmetic, relational, logical) are not
allowed
struct Personnel p1 = {“Fred”, 37, 1.83};
struct Personnel p2;
p2 = p1;
/* Valid. */
if (p1 == p2)
/* Invalid. Won’t compile. */
printf(“People are equaln");
if (strcmp(p1.name, p2.name) == 0 && /* Valid. */
p1.age == p2.age &&
p1.height == p2.height)
printf("People are equaln");

9
Structures and Functions
• Structures may be passed to functions and returned
from functions.
– Like all variables, they are passed by value

10
Pointers to Structures
• Defining pointers is the same as for variables of
primitive types
struct Personnel captain = {“Fred”, 37, 1.83};
struct Personnel *pp;
pp = &captain;
pp->age = 38; /* captain.age is now 38. */

11
Arrays of Structures
• The definition of arrays of structure types is
the same as for arrays of primitive types.
struct Personnel pa[10];

12
Self-Referential Structures
• A structure may not contain a variable of its own type.
struct Node {
int item;
struct Node n; /* Invalid */
};

• However, a structure may contain a pointer, self referential
structure
struct Node {
int item;
struct Node *pn; /* Valid */
};

13
14
Example: A Linked List
• Linked lists come in two basic varieties: singly linked and
doubly linked.
• We describe here a simple version of a singly linked list.
• List consists of a set of nodes, where each node contains an item
and a pointer to another list node.
struct List {
int item;
struct List *next;
};

• (Here we have chosen an int as the contained item. Any other
type(s) may be used.)
15
Singly Linked List
• List is formed by connecting the pointer of one node to the
address of the next.
• We keep a pointer to the head of the list. This permits traversal.
• The end of the list is marked by a NULL pointer.
• Example, to start at the head of the list and traverse to the end
node:
struct List *node = head;
while (node->next != NULL)
node = node->next;
printf(“Last node item: %d“, node->item);
16
Linked-List Properties
• Linked-Lists are useful because they can be grown (or
shrunk) very easily. Unlike arrays, there are no issues
of reallocating memory and copying data.
• Nodes can even be inserted (or removed) from midway
along the list without difficulty (and efficiently).

17
Adding Nodes to a List
• Show example code for adding a node to the end of the list.
• Show example code for adding a node midway through the
list.

18
Splicing in a New Node
•

Remember that everything is manipulated as an address. Consider the pointer variables, eg.,
–
–
–

node
node->next
newnode

is address 0x4D
is address 0xA1
is address 0xB6

0x4D

•

0xA1

Splicing:
newnode->next = node->next; assign to 0xA1
node->next = newnode;
assign to 0xB6
0xB6

0x4D

0xA1
19

Mais conteúdo relacionado

Mais procurados

Lecture19 unionsin c.ppt
Lecture19 unionsin c.pptLecture19 unionsin c.ppt
Lecture19 unionsin c.ppt
eShikshak
 
Friends function and_classes
Friends function and_classesFriends function and_classes
Friends function and_classes
asadsardar
 

Mais procurados (20)

C# program structure
C# program structureC# program structure
C# program structure
 
Structure c
Structure cStructure c
Structure c
 
Structure in c#
Structure in c#Structure in c#
Structure in c#
 
Unit4 C
Unit4 C Unit4 C
Unit4 C
 
Basic of Structure,Structure members,Accessing Structure member,Nested Struct...
Basic of Structure,Structure members,Accessing Structure member,Nested Struct...Basic of Structure,Structure members,Accessing Structure member,Nested Struct...
Basic of Structure,Structure members,Accessing Structure member,Nested Struct...
 
Unit 9. Structure and Unions
Unit 9. Structure and UnionsUnit 9. Structure and Unions
Unit 9. Structure and Unions
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
Strings in c#
Strings in c#Strings in c#
Strings in c#
 
Constant a,variables and data types
Constant a,variables and data typesConstant a,variables and data types
Constant a,variables and data types
 
Lecture19 unionsin c.ppt
Lecture19 unionsin c.pptLecture19 unionsin c.ppt
Lecture19 unionsin c.ppt
 
SPL 14 | Structures in C
SPL 14 | Structures in CSPL 14 | Structures in C
SPL 14 | Structures in C
 
Structure in c sharp
Structure in c sharpStructure in c sharp
Structure in c sharp
 
Learn C# Programming - Structure & Enums
Learn C# Programming - Structure & EnumsLearn C# Programming - Structure & Enums
Learn C# Programming - Structure & Enums
 
Object as function argument , friend and static function by shahzad younas
Object as function argument , friend and static function by shahzad younasObject as function argument , friend and static function by shahzad younas
Object as function argument , friend and static function by shahzad younas
 
[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects
 
Friends function and_classes
Friends function and_classesFriends function and_classes
Friends function and_classes
 
17 structure-and-union
17 structure-and-union17 structure-and-union
17 structure-and-union
 
Friend function & friend class
Friend function & friend classFriend function & friend class
Friend function & friend class
 
Inheritance,constructor,friend function
Inheritance,constructor,friend functionInheritance,constructor,friend function
Inheritance,constructor,friend function
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
 

Destaque

Lec 04. If-Else Statement / Increment and Decrement Operators
Lec 04. If-Else Statement / Increment and Decrement OperatorsLec 04. If-Else Statement / Increment and Decrement Operators
Lec 04. If-Else Statement / Increment and Decrement Operators
Rushdi Shams
 
Lec 13. Introduction to Pointers
Lec 13. Introduction to PointersLec 13. Introduction to Pointers
Lec 13. Introduction to Pointers
Rushdi Shams
 

Destaque (7)

Lec 04. If-Else Statement / Increment and Decrement Operators
Lec 04. If-Else Statement / Increment and Decrement OperatorsLec 04. If-Else Statement / Increment and Decrement Operators
Lec 04. If-Else Statement / Increment and Decrement Operators
 
Lec 13. Introduction to Pointers
Lec 13. Introduction to PointersLec 13. Introduction to Pointers
Lec 13. Introduction to Pointers
 
Lec 18. Recursion
Lec 18. RecursionLec 18. Recursion
Lec 18. Recursion
 
Recursion prog (1)
Recursion prog (1)Recursion prog (1)
Recursion prog (1)
 
Recursion prog
Recursion progRecursion prog
Recursion prog
 
Pointers
PointersPointers
Pointers
 
Type conversion
Type conversionType conversion
Type conversion
 

Semelhante a Structure

Unit4 (2)
Unit4 (2)Unit4 (2)
Unit4 (2)
mrecedu
 
data structure and c programing concepts
data structure and c programing conceptsdata structure and c programing concepts
data structure and c programing concepts
kavitham66441
 
structures and unions in 'C'
structures and unions in 'C'structures and unions in 'C'
structures and unions in 'C'
illpa
 

Semelhante a Structure (20)

User defined data types.pptx
User defined data types.pptxUser defined data types.pptx
User defined data types.pptx
 
Structures and Pointers
Structures and PointersStructures and Pointers
Structures and Pointers
 
1. structure
1. structure1. structure
1. structure
 
Structures in C
Structures in CStructures in C
Structures in C
 
Unit 4 qba
Unit 4 qbaUnit 4 qba
Unit 4 qba
 
Data Structure & aaplications_Module-1.pptx
Data Structure & aaplications_Module-1.pptxData Structure & aaplications_Module-1.pptx
Data Structure & aaplications_Module-1.pptx
 
DS_PPT.ppt
DS_PPT.pptDS_PPT.ppt
DS_PPT.ppt
 
Pointers and Structures
Pointers and StructuresPointers and Structures
Pointers and Structures
 
C++ training
C++ training C++ training
C++ training
 
Structure in C
Structure in CStructure in C
Structure in C
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
 
Programming in C session 3
Programming in C session 3Programming in C session 3
Programming in C session 3
 
Session 6
Session 6Session 6
Session 6
 
Unit4 (2)
Unit4 (2)Unit4 (2)
Unit4 (2)
 
Data structure
 Data structure Data structure
Data structure
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
data structure and c programing concepts
data structure and c programing conceptsdata structure and c programing concepts
data structure and c programing concepts
 
SPC Unit 5
SPC Unit 5SPC Unit 5
SPC Unit 5
 
Structure & union
Structure & unionStructure & union
Structure & union
 
structures and unions in 'C'
structures and unions in 'C'structures and unions in 'C'
structures and unions in 'C'
 

Mais de Frijo Francis

Mais de Frijo Francis (8)

Data type
Data typeData type
Data type
 
C programming language
C programming languageC programming language
C programming language
 
Break and continue
Break and continueBreak and continue
Break and continue
 
6 enumerated, typedef
6 enumerated, typedef6 enumerated, typedef
6 enumerated, typedef
 
5bit field
5bit field5bit field
5bit field
 
4 dynamic memory allocation
4 dynamic memory allocation4 dynamic memory allocation
4 dynamic memory allocation
 
Union
UnionUnion
Union
 
1file handling
1file handling1file handling
1file handling
 

Último

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Krashi Coaching
 

Último (20)

Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 

Structure

  • 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 user-defined types. • The most common user-defined type is a structure, defined by the keyword struct. 2
  • 3. Structures • A structure is a collection of one or more variables, possibly of different types, grouped together under a single name • Structures are user-defined aggregate types. • They assist program organisation by – Grouping logically related data, and giving this set of variables a higher-level name and more abstract representation. – Reducing the number of parameters that need to be passed between functions. – Providing another means to return multiple values from a function. 3
  • 4. Structure Syntax • A structure is defined by the keyword struct followed by a set of variables enclosed in braces. • Consider the following structure to represent a person’s details. struct Personnel { char name[100]; int age; double height; }; • The variables name, age and height are called members of the structure type Personnel. 4
  • 5. Declaring Structure Variables • There are two ways to define variables of a particular structure type. 1. Declare them at the structure definition. struct Personnel { char name[100]; int age; double height; } p1, p2, p3; /* Define 3 variables */ 2. Define the variables at some point after the structure definition. struct Personnel p1, p2, p3; /* Define 3 variables */ 5
  • 6. Initialising Structure Variables • A structure may be initialised when it is defined using brace notation. struct Personnel captain = {“Fred”, 37, 1.83}; • The order of values in the initialise list matches the order of declarations in the structure. 6
  • 7. Accessing Members • Members of a structure type may be accessed via the “.” member operator. struct Personnel captain; strcpy(captain.name, “Fred”); captain.age = 37; captain.height = 1.83; printf(“%s is %d years old.”, captain.name, captain.age); 7
  • 8. Nested Structures • Structures may be defined inside other structures. struct first { struct second { int a; }s; double amount; }f; • To access lower-level members, need to use member operator multiple times. f.s.a = 2.1; f.amount = 75.4; 8
  • 9. Operations on Structures • Structure types only support one of the operations that are permitted on primitive types. – Assignment (ie., copying) is permitted – All other operations (ie., arithmetic, relational, logical) are not allowed struct Personnel p1 = {“Fred”, 37, 1.83}; struct Personnel p2; p2 = p1; /* Valid. */ if (p1 == p2) /* Invalid. Won’t compile. */ printf(“People are equaln"); if (strcmp(p1.name, p2.name) == 0 && /* Valid. */ p1.age == p2.age && p1.height == p2.height) printf("People are equaln"); 9
  • 10. Structures and Functions • Structures may be passed to functions and returned from functions. – Like all variables, they are passed by value 10
  • 11. Pointers to Structures • Defining pointers is the same as for variables of primitive types struct Personnel captain = {“Fred”, 37, 1.83}; struct Personnel *pp; pp = &captain; pp->age = 38; /* captain.age is now 38. */ 11
  • 12. Arrays of Structures • The definition of arrays of structure types is the same as for arrays of primitive types. struct Personnel pa[10]; 12
  • 13. Self-Referential Structures • A structure may not contain a variable of its own type. struct Node { int item; struct Node n; /* Invalid */ }; • However, a structure may contain a pointer, self referential structure struct Node { int item; struct Node *pn; /* Valid */ }; 13
  • 14. 14
  • 15. Example: A Linked List • Linked lists come in two basic varieties: singly linked and doubly linked. • We describe here a simple version of a singly linked list. • List consists of a set of nodes, where each node contains an item and a pointer to another list node. struct List { int item; struct List *next; }; • (Here we have chosen an int as the contained item. Any other type(s) may be used.) 15
  • 16. Singly Linked List • List is formed by connecting the pointer of one node to the address of the next. • We keep a pointer to the head of the list. This permits traversal. • The end of the list is marked by a NULL pointer. • Example, to start at the head of the list and traverse to the end node: struct List *node = head; while (node->next != NULL) node = node->next; printf(“Last node item: %d“, node->item); 16
  • 17. Linked-List Properties • Linked-Lists are useful because they can be grown (or shrunk) very easily. Unlike arrays, there are no issues of reallocating memory and copying data. • Nodes can even be inserted (or removed) from midway along the list without difficulty (and efficiently). 17
  • 18. Adding Nodes to a List • Show example code for adding a node to the end of the list. • Show example code for adding a node midway through the list. 18
  • 19. Splicing in a New Node • Remember that everything is manipulated as an address. Consider the pointer variables, eg., – – – node node->next newnode is address 0x4D is address 0xA1 is address 0xB6 0x4D • 0xA1 Splicing: newnode->next = node->next; assign to 0xA1 node->next = newnode; assign to 0xB6 0xB6 0x4D 0xA1 19