0% found this document useful (0 votes)
7 views34 pages

Understanding Structures in Programming

The document provides an overview of structures, unions, and enums in programming, focusing on the definition, usage, and manipulation of structures. It covers topics such as defining structures, accessing members, passing structures as function arguments, and initializing structures. Additionally, it discusses arrays of structures and the use of typedef for creating new data types.

Uploaded by

niyonshutiisaac7
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views34 pages

Understanding Structures in Programming

The document provides an overview of structures, unions, and enums in programming, focusing on the definition, usage, and manipulation of structures. It covers topics such as defining structures, accessing members, passing structures as function arguments, and initializing structures. Additionally, it discusses arrays of structures and the use of typedef for creating new data types.

Uploaded by

niyonshutiisaac7
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Fundamentals of Programming

STRUCTURES, UNIONS AND ENUMS

1| | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


Agenda
• What is structure 3
• Defining structure 4, 5
• Parameter Passing in a Function
• Syntax of structure • Returning structures
• Creating structure variable
• Structures and functions
• Accessing members of a structure
• Passing structure member as argument
• Typedef keyword 14, 15
• Pointer to structure declaration
• Passing structure variable as argument
• Accessing structure members using pointer • Passing pointers to structures as arguments
• Structure example ….. • Returning a structure variable from the function
• A compact form • Returning a pointer to a structure from the function
• Processing a structure • Passing array of structures as argument
• Comparison of Structure Variables
• Self referential structures
• Arrays of Structures
• Arrays within Structures
• Defining data type: using typedef
• Structure Initialization

2| | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


What is a Structure?
STUDENT 1 STUDENT 2 STUDENT 3
Student name Mahoro Peace Student name Gaju Ethan Student name Mucyo Nathan
Age 17 Age 17 Age 17
Roll number 201901 Roll number 201902 Roll number 201903
Marks 89.8 Marks 92.5 Marks 84.7

Char* st1Name = “Mahoro Peace”; Char* st2Name = “Gaju Ethan”; Char* st3Name = “Mucyo Nathan”;
Int st1Age = 17; Int st2Age = 17; Int st3Age = 17;
Int st1RollNumber = 201901 Int st2RollNumber = 201902 Int st3RollNumber = 201903
Float st1Marks = 89.8 Float st2Marks = 92.5 Float st3Marks = 84.7

• How can we store the data of this kind? Can array help us to store this data?
– The answer is NO! Array can store more than one elements but all must be of the same data type.
– We need other way to deal with the data of this kind. => STRUCTURE

3| | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


What is a Structure?
• It is a convenient tool for handling a group of logically related data items.
– Student name, roll number, and marks
– Real part and complex part of a complex number

• This is our first look at a non-trivial data structure.


– Helps in organizing complex data in a more meaningful way.

• The individual structure elements are called members.


• In brief, a structure is a user defined data type that can be used to group elements of
different types into a single type.

4| | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


Defining a Structure
• The composition of a structure may be defined as:
struct tag {
member 1;
member 2;
:
member m;
};
– struct is the required keyword.
– tag is the name of the structure.
– member 1, member 2, … are individual member declarations.

5| | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


Defining a Structure
• The individual members can be ordinary variables, pointers, arrays, or
other structures.
– The member names within a particular structure must be distinct from one another.
– A member name can be the same as the name of a variable defined outside of the
structure.

• Once a structure has been defined, individual structure-type variables


can be declared as:
struct tag variable_1, variable_2, …, variable_n;

6| | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


Structure Example
⚫ A structure definition:
struct student {
char name[30];
int roll_number;
int total_marks;
char dob[10];
};

⚫ Defining structure variables:


struct student a1, a2, a3;
}

A new data-type
7| | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024
A Compact Form
• It is possible to combine the declaration of the structure with that of the
structure variables:

struct tag {
member 1;
member 2;
:
member m;
} variable_1, variable_2,…, variable_n;

• In this form, “tag” is optional.

8| | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


Example
struct student {
char name[30];
int roll_number;
int total_marks;
char dob[10];
} a1, a2, a3;
Equivalent
declarations
struct {
char name[30];
int roll_number;
int total_marks;
char dob[10];
} a1, a2, a3;

9| | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


Processing a Structure
• The members of a structure are processed individually, as separate
entities.

• A structure member can be accessed by writing


[Link]

where variable refers to the name of a structure-type variable, and


member refers to the name of a member within the structure.

• Examples:
– [Link], [Link], a1.roll_number, [Link];

10 | | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


Example: Complex number addition
#include <stdio.h> printf (“\n %f + %f j”, [Link],
main() Scope [Link]);
{ }
struct complex
restricted
{ within
float real; main() Structure definition
float complex;
} first, second, sum; And
Variable Declaration
scanf (“%f %f”, & [Link], & [Link]);
scanf (“%f %f”, & [Link], & [Link]);

[Link] = [Link] + [Link];


[Link] = [Link] + [Link];
Reading a member
variable

Fundamentals
11 | Accessing
| membersof Programming - Aphrodice Rwagaju | 09 May 2024
Comparison of Structure Variables
• Unlike arrays, group operations can be performed with structure
variables.
– A structure variable can be directly assigned to another structure variable of the
same type.
a1 = a2;
• All the individual members get assigned.
– Two structure variables can be compared for equality or inequality.
if (a1 = = a2) …….
• Compare all members and return 1 if they are equal; 0 otherwise.

12 | | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


Arrays of Structures
⚫ Once a structure has been defined, we can declare an array of
structures.
struct student class[50];

– The individual members can be accessed as:


• class[i].name
• class[5].roll_number

13 | | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


Arrays within Structures
• A structure member can be an array:
struct student {
char name[30];
int roll_number;
int marks[5];
char dob[10];
} a1, a2, a3;

• The array element within the structure can be accessed as:


[Link][2]

14 | | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


Defining data type: using typedef
• One may define a structure data-type with a single name.

• General syntax:
typedef struct {
member-variable1;
member-variable2;
.
.
member-variableN;
} tag;

• tag is the name of the new data-type.

15 | | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


typedef : An example
typedef struct{

float real;

float imag;

} _COMPLEX;

_COMPLEX a,b,c;

16 | | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


Structure Initialization
• Structure variables may be initialized following similar rules of an array. The values are
provided within the second braces separated by commas.

• An example:

_COMPLEX a={1.0,2.0}, b={-3.0,4.0};

[Link]=1.0; [Link]=2.0;
[Link]=-3.0; [Link]=4.0;

17 | | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


Parameter Passing in a Function
• Structure variables could be passed as parameters like any other variable.
Only the values will be copied during function invocation.

void swap(_COMPLEX a, _COMPLEX b)


{
_COMPLEX tmp;

tmp=a;
a=b;
b=tmp;
}

18 | | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


An example program
#include <stdio.h>
void print(_COMPLEX a)
typedef struct{ {
float real; printf("(%f , %f) \n",[Link],[Link]);
float imag; }
} _COMPLEX;
void swap(_COMPLEX a, _COMPLEX b) main()
{ {
_COMPLEX tmp; _COMPLEX x={4.0,5.0},y={10.0,15.0};

tmp=a; print(x); print(y);


a=b; swap(x,y);
b=tmp; print(x); print(y);
} }

19 | | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


Returning structures
⚫ It is also possible to return structure values from a function. The return data
type of the function should be as same as the data type of the structure itself.

COMPLEX add (COMPLEX a, COMPLEX b)


{
COMPLEX tmp;

[Link] = [Link]+[Link]; Direct arithmetic


[Link] = [Link]+[Link]; operations are not
possible with
return(tmp); Structure variables.
}

20 | | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


Passing structure member as argument
• Like other variables, we can pass structures members as arguments to a
function struct student{
char name[30];
int age;
int roll_no;
float marks;
};
void print(char name[], int age, int rollNo, float marks){
printf(“%s %d %d %.2f”, name, age, rollNo, marks);
}
int main(){
struct student st1 = {“Mahoro Peace”, 17, 201912, 87.8};
print([Link], [Link], st1.roll_no, [Link]);
}

21 | | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


Structure member as argument- Call by reference
• Instead of passing the copies of the structure members, we can pass their
addresses or references.
struct charset {
char s;
int i;
};
void keyValue(char* s, int*i){
scanf(“%c %d”, s, i);
} The “.” operator
int main(){ is evaluated before
int j; the “&” operator and
struct charset cs; this is why we don’t
keyValue(&cs.s, &cs.i); use &(cs.s) or &(cs.i)
printf(“%c %d”, cs.s, cs.i);
return 0;
}
22 | | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024
Passing structure variable as argument
• Instead of passing structure members individually, it is good practice to
pass structure variable as an argument.

• Unlike arrays, name of the structures are not pointers.

• Hence, passing structure variable is a pass by value not as by reference


struct point{ int main(){
int x; struct point p1 = {12, 17};
int y; struct point p2 = {22, 43};
}; print(p1);
Output:
void print(struct point p){ print(p2);
12 17
printf(“%d %d\n”, p.x, p.y); return 0; 22 43
} }
23 | | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024
Passing pointer to structure as an argument
• If the size of the structure is very large, it is not good practice to pass a copy of the
whole structure.

• In this case, better to pass the address of the structure.

• We use arrow (->) operator to access the structure members inside the called function

struct point{ int main(){


int x; struct point p1 = {12, 17};
int y; struct point p2 = {22, 43};
}; print(&p1);
void print(struct point *ptr){ print(&p2); Output:
printf(“%d %d\n”, ptr -> x, ptr -> y); return 0; 12 17
22 43
} }

24 | | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


Returning structure variable from a function
• Returning a structure variable from a function is similar to returning a variable from a
function.
struct point{
int x;
int main(){
int y;
}; struct point p1 = {12, 17};
struct point edit(struct point p){ struct point p2 = {22, 43};
(p.x)++; p1 = edit(p1);
p.y = p.y+14; p2 = edit(p2);
return p;
print(p1);
}
print(p2); Output:
void print(struct point p){
return 0; 13 31
printf(“%d %d\n”, p.x, p.y);
23 57
} }

25 | | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


Returning a pointer structure from a function
struct point{ int main(){
int x; struct point *ptr1, *ptr2;
int y;
ptr1 = func(12, 17);
};
struct point* func(int a, int b){
ptr2 = func(22, 43);
struct point *ptr = (struct point *)malloc(sizeof(struct point)); print(ptr1);
ptr->x = a; print(ptr2);
ptr->y = b+14; free(ptr1);
return ptr; free(ptr2);
}
return 0;
void print(struct point *ptr){ Output:
}
printf(“%d %d\n”, ptr->x, ptr->y); 12 31
} 22 57

26 | | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


Passing array of structures as argument

▪ Example:
struct alphabet{
int index;
char letter;
};

struct alphabet arr[3] = {{1,’A’},{2,’B’} ,{3,’C’}};

▪ The compiler will allocate contiguous block of memory for the data members of the
structure.

27 | | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


Passing array of structures as argument - Example
struct point{ int main(){
int x; struct point arr[2] = {{12,17},{22,43}};
int y; print(arr);
}; return 0;
}
void print(struct point arr[]){
int i;
for(i=0; i<2; i++)
printf(“%d %d\n”, arr[i].x, arr[i].y);
Output:
}
12 17
22 43

28 | | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


Self referential structures
• Self referential structures are those structures in which one or more pointers point to
the structure of the same type.

struct selfRef{
int x;
struct selfRef *ptr;
};

29 | | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


UNIONS
• Unions are conceptually similar to structures. The syntax to declare/define
a union is also similar to that of a structure. The only differences is in terms
of storage.

• In structure each member has its own storage location, whereas all
members of a union uses a single shared memory location which is equal
to the size of its largest data member.

30 | | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


UNIONS

31 | | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


Enumerations
• Enumeration or simply enum is a user defined datatype in C language. It is
used to assign names to the integral constants which makes a program
easy to read and maintain.

• The keyword “enum” is used to declare an enumeration.

• They are mainly used to assign names to integral constants, the names
make a program easy to read and maintain.

• Syntax:
• enum enum_name{const1, const2, ....... };

32 | | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


Enumerations
• There are two ways to define the variables of enum type as follows.
• enum week{sunday, monday, tuesday, wednesday, thursday, friday, saturday};
• enum week day;

• Example of enum:
#include<sdtio.h>
enum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun};
enum day{Mond, Tues, Wedn, Thurs, Frid=18, Satu=11, Sund};
int main() {
printf("The value of enum week: %d\t%d\t%d\t%d\t%d\t%d\t%d\n\n", Mon, Tue, Wed, Thur, Fri, Sat, Sun);
printf("The default value of enum day: %d\t%d\t%d\t%d\t%d\t%d\t%d",Mond , Tues, Wedn, Thurs, Frid,
Satu, Sund);
return 0;
}

33 | | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024


End of file !

34 | | Fundamentals of Programming - Aphrodice Rwagaju | 09 May 2024

You might also like