0% found this document useful (0 votes)
18 views

Unit 4 Final Notes

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)
18 views

Unit 4 Final Notes

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
You are on page 1/ 21

C Structures (structs)

❮ PreviousNext ❯
Structures (also called structs) are a way to group several related variables
into one place. Each variable in the structure is known as a member of the
structure.

For example: If I have to write a program to store Student information, which will have
Student's name, age, branch, permanent address, father's name etc, which included
string values, integer values etc, how can I use arrays for this problem, I will require
something which can hold data of different types together.

In structure, data is stored in form of records.

Defining a structure

struct keyword is used to define a structure. struct defines a new data type which is a

collection of primary and derived data types.


Syntax to Define a Structure in C
struct [structure_tag]

//member variable 1

//member variable 2

//member variable 3

...

}[structure_variables];

struct structName

// structure definition

Data_type1 member_name1;

Data_type2 member_name2;
Data_type2 member_name2;

};

Example:

struct MyStructure { // Structure declaration


int myNum; // Member (int variable)
char myLetter; // Member (char variable)
}; // End the structure with a semicolon

To access the structure, you must create a variable of it.

Use the struct keyword inside the main() method, followed by the name of
the structure and then the name of the structure variable:

Create a struct variable with the name "s1":

struct myStructure {
int myNum;
char myLetter;
};

int main() {
struct myStructure s1;
return 0;
}

Access Structure Members


To access members of a structure, use the dot syntax ( .):

Example
// Create a structure called myStructure
struct myStructure {
int myNum;
char myLetter;
};

int main() {
// Create a structure variable of myStructure called s1
struct myStructure s1;
// Assign values to members of s1
s1.myNum = 13;
s1.myLetter = 'B';
// Print values
printf("My number: %d\n", s1.myNum);
printf("My letter: %c\n", s1.myLetter);
return 0;
}

Now you can easily create multiple structure variables with different values,
using just one structure:

Example
// Create different struct variables
struct myStructure s1;
struct myStructure s2;

// Assign values to different struct variables


s1.myNum = 13;
s1.myLetter = 'B';

s2.myNum = 20;
s2.myLetter = 'C';

Example2:

1. struct employee
2. { int id;
3. char name[50];
4. float salary;
5. };

Now write given code inside the main() function.

1. struct employee e1, e2;

The variables e1 and e2 can be used to access the values stored in the structure.

2nd way:

Let's see another way to declare variable at the time of defining the structure.

1. struct employee
2. { int id;
3. char name[50];
4. float salary;
5. }e1,e2;

simple example of structure in C language.

1. #include<stdio.h>
2. #include <string.h>
3. struct employee
4. { int id;
5. char name[50];
6. }e1; //declaring e1 variable for structure
7. int main( )
8. {
9. //store first employee information
10. e1.id=101;
11. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
12. //printing first employee information
13. printf( "employee 1 id : %d\n", e1.id);
14. printf( "employee 1 name : %s\n", e1.name);
15. return 0;
16. }

Example of the structure in C language to store many employees information.

1. #include<stdio.h>
2. #include <string.h>
3. struct employee
4. { int id;
5. char name[50];
6. float salary;
7. }e1,e2; //declaring e1 and e2 variables for structure
8. int main( )
9. {
10. //store first employee information
11. e1.id=101;
12. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
13. e1.salary=56000;
14. //store second employee information
15. e2.id=102;
16. strcpy(e2.name, "James Bond");
17. e2.salary=126000;
18. //printing first employee information
19. printf( "employee 1 id : %d\n", e1.id);
20. printf( "employee 1 name : %s\n", e1.name);
21. printf( "employee 1 salary : %f\n", e1.salary);
22. //printing second employee information
23. printf( "employee 2 id : %d\n", e2.id);
24. printf( "employee 2 name : %s\n", e2.name);
25. printf( "employee 2 salary : %f\n", e2.salary);
26. return 0;
27. }

#include <stdio.h>
#include <string.h>

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};

int main( ) {

struct Books Book1; /* Declare Book1 of type Book */


struct Books Book2; /* Declare Book2 of type Book */

/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;

/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;

/* print Book1 info */


printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);

/* print Book2 info */


printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id);

return 0;
}
Output:
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
C Array of Structures-

Why use an array of structures?

Consider a case, where we need to store the data of 5 students. We can store it by using the
structure as given below.

1. #include<stdio.h>
2. struct student
3. {
4. char name[20];
5. int id;
6. float marks;
7. };
8. void main()
9. {
10. struct student s1,s2,s3;
11. int dummy;
12. printf("Enter the name, id, and marks of student 1 ");
13. scanf("%s %d %f",s1.name,&s1.id,&s1.marks);
14. scanf("%c",&dummy);
15. printf("Enter the name, id, and marks of student 2 ");
16. scanf("%s %d %f",s2.name,&s2.id,&s2.marks);
17. scanf("%c",&dummy);
18. printf("Enter the name, id, and marks of student 3 ");
19. scanf("%s %d %f",s3.name,&s3.id,&s3.marks);
20. scanf("%c",&dummy);
21. printf("Printing the details....\n");
22. printf("%s %d %f\n",s1.name,s1.id,s1.marks);
23. printf("%s %d %f\n",s2.name,s2.id,s2.marks);
24. printf("%s %d %f\n",s3.name,s3.id,s3.marks);
25. }

Output

Enter the name, id, and marks of student 1 James 90 90


Enter the name, id, and marks of student 2 Adoms 90 90
Enter the name, id, and marks of student 3 Nick 90 90
Printing the details....
James 90 90.000000
Adoms 90 90.000000
Nick 90 90.000000
In the above program, we have stored data of 3 students in the structure. However, the
complexity of the program will be increased if there are 20 students. In that case, we will
have to declare 20 different structure variables and store them one by one. This will always
be tough since we will have to declare a variable every time we add a student. Remembering
the name of all the variables is also a very tricky task. However, c enables us to declare an
array of structures by using which, we can avoid declaring the different structure variables;
instead we can make a collection containing all the structures that store the information of
different entities.

Array of Structures in C-

An array of structres in C can be defined as the collection of multiple structures variables


where each variable contains information about different entities. The array of structures in
C are used to store information about multiple entities of different data types. The array of
structures is also known as the collection of structures.

Let's see an example of an array of structures that stores information of 5 students and prints
it.

1. #include<stdio.h>
2. #include <string.h>
3. struct student{
4. int rollno;
5. char name[10];
6. };
7. int main(){
8. int i;
9. struct student st[5];
10. printf("Enter Records of 5 students");
11. for(i=0;i<5;i++){
12. printf("\nEnter Rollno:");
13. scanf("%d",&st[i].rollno);
14. printf("\nEnter Name:");
15. scanf("%s",&st[i].name);
16. }
17. printf("\nStudent Information List:");
18. for(i=0;i<5;i++){
19. printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
20. }
21. return 0;
22. }

Output:

Enter Records of 5 students


Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz

Student Information List:


Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz
C Pointers
The pointer in C language is a variable which stores the address of another variable. This
variable can be of type int, char, array, function, or any other pointer. The size of the
pointer depends on the architecture. However, in 32-bit architecture the size of a
pointer is 2 byte.

Pointer Syntax
int *p

Assigning addresses to Pointers


int *p, c ;
c = 5;
p = &c;

Get Value of Thing Pointed by Pointers


To get the value of the thing pointed by the pointers, we use the * operator. For example:

int *p, c ;
c = 5;
p = &c;
printf(“%d”, *p);

Output: 5

Here, the address of c is assigned to the pc pointer. To get the value stored in that address, we
used *pc .

Changing Value Pointed by Pointers

Let's take an example.

int *pc, c;
c = 5;
pc = &c;
printf(“%d”,c);
printf(“%d”,*pc);
We have assigned the address of c to the pc pointer.
Then, we changed the value of c to 1. Since pc and the address of c is the
same, *pc gives us 1.
Let's take another example.

int *pc, c;
c = 5;
*pc = &c;
*pc = 1;
printf(“%d”, *pc);
printf(“%d”,c);
We have assigned the address of c to the pc pointer.
Then, we changed *pc to 1 using *pc = 1; . Since pc and the address of c is the
same, c will be equal to 1.
Let's take one more example.

int *pc , c , d;
c = 5;
d = 15;
pc = &c;
printf(“%d”, *pc);
pc = &d);
printf(“%d”, *pc);
Example: Working of Pointers

Let's take a working example.

#include <stdio.h>
int main()
{
int* pc, c;

c = 22;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 22

pc = &c;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 22

c = 11;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 11

*pc = 2;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 2
return 0;
}

Output

Address of c: 2686784
Value of c: 22

Address of pointer pc: 2686784


Content of pointer pc: 22

Address of pointer pc: 2686784


Content of pointer pc: 11

Address of c: 2686784
Value of c: 2

Explanation of the program


1. int* pc, c;

Here, a pointer pc and a normal variable c, both of type int, is created.


Since pc and c are not initialized at initially, pointer pc points to either no address or a
random address. And, variable c has an address but contains random garbage value.
2. c = 22;

This assigns 22 to the variable c. That is, 22 is stored in the memory location of
variable c.

3. pc = &c;

This assigns the address of variable c to the pointer pc.

4. c = 11;

This assigns 11 to variable c.

5. *pc = 2;

This change the value at the memory location pointed by the pointer pc to 2.
#include <stdio.h>
int main()
{
//Variable declaration
int num = 10;

//Pointer declaration
int *p;

//Assigning address of num to the pointer p


p = #

printf("Address of variable num is: %p", p);


return 0;
}
Output:

Address of variable num is: 0x7fff5694dc58

Pointers – Operators that are used with Pointers


Lets discuss the operators & and * that are used with Pointers in C.

“Address of”(&) Operator


We have already seen in the first example that we can display the address of a variable
using ampersand sign. I have used &num to access the address of variable num. The &
operator is also known as “Address of” Operator.

printf("Address of var is: %p", &num);


Point to note: %p is a format specifier which is used for displaying the address in hex
format.
Now that you know how to get the address of a variable but how to store that address
in some other variable? That’s where pointers comes into picture. As mentioned in the
beginning of this guide, pointers in C programming are used for holding the address of
another variables.

“Value at Address”(*) Operator


The * Operator is also known as Value at address operator.

How to declare a pointer?

int *p1 /*Pointer to an integer variable*/


double *p2 /*Pointer to a variable of data type double*/
char *p3 /*Pointer to a character variable*/
float *p4 /*pointer to a float variable*/
The above are the few examples of pointer declarations. If you need a pointer to store the
address of integer variable then the data type of the pointer should be int. Same case
is with the other data types.

By using * operator we can access the value of a variable through a pointer.


For example:

double a = 10;
double *p;
p = &a;
*p would give us the value of the variable a. The following statement would display 10 as
output.

printf("%d", *p);
Similarly if we assign a value to *pointer like this:

*p = 200;
It would change the value of variable a. The statement above will change the value of a
from 10 to 200.

Example of Pointer demonstrating the use of & and *


#include <stdio.h>
int main()
{
/* Pointer of integer type, this can hold the
* address of a integer type variable.
*/
int *p;

int var = 10;

/* Assigning the address of variable var to the pointer


* p. The p can hold the address of var because var is
* an integer type variable.
*/
p= &var;

printf("Value of variable var is: %d", var);


printf("\nValue of variable var is: %d", *p);
printf("\nAddress of variable var is: %p", &var);
printf("\nAddress of variable var is: %p", p);
printf("\nAddress of pointer p is: %p", &p);
return 0;
}
Output:

Value of variable var is: 10


Value of variable var is: 10
Address of variable var is: 0x7fff5ed98c4c
Address of variable var is: 0x7fff5ed98c4c
Address of pointer p is: 0x7fff5ed98c50

Can you guess the output of following C program?

#include <stdio.h>
int main()
{
int var =10;
int *p;
p= &var;

printf ( "Address of var is: %p", &var);


printf ( "\nAddress of var is: %p", p);

printf ( "\nValue of var is: %d", var);


printf ( "\nValue of var is: %d", *p);
printf ( "\nValue of var is: %d", *( &var));

/* Note I have used %p for p's value as it represents an address*/


printf( "\nValue of pointer p is: %p", p);
printf ( "\nAddress of pointer p is: %p", &p);

return 0;
}
Output:

Address of var is: 0x7fff5d027c58


Address of var is: 0x7fff5d027c58
Value of var is: 10
Value of var is: 10
Value of var is: 10
Value of pointer p is: 0x7fff5d027c58
Address of pointer p is: 0x7fff5d027c50
Write a c program to pint the sum of two number using pointer
Linked List:
Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements
are not stored at a contiguous location; the elements are linked using pointers. They
includes a series of connected nodes. Here, each node stores the data and the
address of the next node.

Why Linked List?


Arrays can be used to store linear data of similar types, but arrays have the following
limitations.
• The size of the arrays is fixed: So we must know the upper limit on the
number of elements in advance. Also, generally, the allocated memory is
equal to the upper limit irrespective of the usage.
• Insertion of a new element / Deletion of a existing element in an array of
elements is expensive: The room has to be created for the new elements and
to create room existing elements have to be shifted but in Linked list if we
have the head node then we can traverse to any node through it and insert
new node at the required position.
For example, in a system, if we maintain a sorted list of IDs in an array id[].
id[] = [1000, 1010, 1050, 2000, 2040].
And if we want to insert a new ID 1005, then to maintain the sorted order, we have to
move all the elements after 1000 (excluding 1000).
Deletion is also expensive with arrays until unless some special techniques are
used. For example, to delete 1010 in id[], everything after 1010 has to be moved due
to this so much work is being done which affects the efficiency of the code.
Advantages over arrays:
1. Dynamic Array.
2. Ease of Insertion/Deletion.
Drawbacks:
1. Random access is not allowed. We have to access elements sequentially
starting from the first node(head node). So we cannot do binary search with
linked lists efficiently with its default implementation. Read about it here.
2. Extra memory space for a pointer is required with each element of the list.
3. Not cache friendly. Since array elements are contiguous locations, there is
locality of reference which is not there in case of linked lists.
Representation:
A linked list is represented by a pointer to the first node of the linked list. The first
node is called the head. If the linked list is empty, then the value of the head points
to NULL.
Each node in a list consists of at least two parts:
1. A Data Item (we can store integer, strings or any type of data).
2. Pointer (Or Reference) to the next node (connects one node to another) or An
address of another node
In C, we can represent a node using structures. Below is an example of a linked list
node with integer data.

// A linked list node


struct Node {
int data;
struct Node* next;
};

Types of Linked List:

1. Singly Linked List

It is the most common. Each node has data and a pointer to the next node.
Singly linked list

Node is represented as:

struct node {
int data;
struct node *next;
}

2. Doubly Linked List

We add a pointer to the previous node in a doubly-linked list. Thus, we can go in


either direction: forward or backward.

Doubly linked list

A node is represented as

struct node {
int data;
struct node *next;
struct node *prev;
}

3. Circular Linked List

A circular linked list is a variation of a linked list in which the last element is linked to
the first element. This forms a circular loop.
Circular linked list
A circular linked list can be either singly linked or doubly linked.

• for singly linked list, next pointer of last item points to the first item

• In the doubly linked list, prev pointer of the first item points to the last item as
well.

4. Circular Doubly Linked List:

A circular doubly linked list is a mixture of a doubly linked list and a circular linked
list. Like the doubly linked list, it has an extra pointer called the previous pointer, and
similar to the circular linked list, its last node points at the head node. This type of
linked list is the bi-directional list. So, you can traverse it in both directions.

You might also like