0% found this document useful (0 votes)
834 views43 pages

PPS Unit 4 Notes Full

The document provides notes on pointers and structures in C programming. It discusses pointer declaration and initialization, pointer operations like incrementing and decrementing, adding or subtracting integers from pointers. It also covers pointer compatibility based on data type size and dereferencing. Structures are defined including array of structures, nested structures, passing structures to functions. Unions and enumerated data types are also mentioned.

Uploaded by

sirisha
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)
834 views43 pages

PPS Unit 4 Notes Full

The document provides notes on pointers and structures in C programming. It discusses pointer declaration and initialization, pointer operations like incrementing and decrementing, adding or subtracting integers from pointers. It also covers pointer compatibility based on data type size and dereferencing. Structures are defined including array of structures, nested structures, passing structures to functions. Unions and enumerated data types are also mentioned.

Uploaded by

sirisha
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/ 43

Programming for problem solving unit 4 Notes

Matrusri Engineering College


Subject:Programming for problem solving
Academic Year :2023-2024
Unit 4-Notes

Unit – IV
Pointers: Pointer declaration, compatibility, Operations on pointers, Pointers and arrays, Pointers
and functions.
Structures: Structure definition, Array of structures, Nested structures, Passing structure to
functions,Pointers and structures, Self-referential structures, Unions, enumerated data types.

Pointers: Pointer declaration

Definition:
Pointers: A pointer is a variable that holds the address of another variable. The pointer variable

contains only the address of the referenced variable not the value stored at that address.

Some of the advantages of using pointers are as follows

1. Pointers are more efficient in handling arrays and data tables

2. Pointers are used with function to return multiple values

3. Pointers allow C to support dynamic memory management

4. Pointers provide an efficient tool for manipulating dynamic data structures such as

structures, linked list, stacks, queues, trees etc

5. Pointers reduce length and complexity of program

6. Pointers reduce program execution time and saves data storage space in memory.

Disadvantages of pointers

1. One of the disadvantage of using pointer is that program may crash if sufficient memory

is not available at run time to store pointers.

Pointer uses two basic operators

1. The address operator (&): It gives address of an object

1
Programming for problem solving unit 4 Notes

2. The indirection operator (*):It is used to accesses the object the pointer points to.

Declaring a pointer variable:

The general syntax of declaring pointer variable is

Datatype *ptrname;

Data type: It specifies the type of the pointer variable that you want to declare like (int, float, char,
double or void)

* (Asterisk): tells the compiler that you are creating a pointer variable and ptrname specifies the name
of the pointer variable.

Example: int *p; // declares a pointer variable p of integer type

float *temp;// declares a pointer variable temp of float data type

Initialization of pointer variable: Similar to the initialization of other variables at the time of their
declaration, you can also initialize the pointer variable by assigning address of other variables to them.

Syntax

Datatype *ptrname = expression;

Where

Datatype: It can be any basic data type,

ptrname is a pointer variable

expression can be any constant value or any variable containing value.

/ *program to illustrate declaration and initialization */

#include<stdio.h>

2
Programming for problem solving unit 4 Notes

void main()

int *ptr; / /declaration of pointer variable

int a=10;

ptr=&a; / /initialization of pointer variable

printf(“the value of a=%d\”,a);

printf(“the value of a using pointer=%d\n”,*ptr);

printf(“the address of a=%u\n”,ptr);

Output:

The value of a=10

The value of a using pointer=10

The address of a =32200

Using the address of (&) operator: A computer uses memory to store the instructions of different
programs and the values of different variables. Since memory is a sequential collection of storage cells,
each cell has an address. When you declare a variable, the operating system allocates memory according
to the size of the data type of that variable. In this memory location, the value of the variable is stored.

Example : int a=100;

This statement request the operating system to allocate two bytes of space in memory and stores

100 in that location.

a ----------→variable name

100------------value of the variable

1500 ----------the address of the memory location

By using the address of (&) operator, you can determine the address of a variable.
3
Programming for problem solving unit 4 Notes

4
Programming for problem solving unit 4 Notes

5
Programming for problem solving unit 4 Notes

Pointer Compatibility:

The rules for assigning one pointer to another are tighter than the rules for
numeric types. For example, you can assign an int value to a double variable without
using a type conversion, but you can’t do the same for pointers to these two types.•

1.Basic pointer Compatibility

2.Pointer Size Compatibility

3. Pointer Dereferencing compatibility

1.Basic pointer Compatibility

We can assign an int valur to double variable without type conversion,but the same cannot
be true for pointers.

Example Program

#include,stdio.h>

int main()

int n=5;

long double x;

int *pi=&n;

long double *pld=&x;

x=n;

pld=pi;

return 0;

Pointer Size Compatibility

• Size of all pointers is the same; i.e.; every pointer variable holds the address of one
memory location. But the size of variable that the pointer points to can be different.

• Size of the type that a pointer points to is same as its data size.

• Size is dependent on type; not on the value.


6
Programming for problem solving unit 4 Notes

Dereferencing Compatibility

• Dereference type is the type of variable that the pointer is referencing.

• It is usually invalid to assign a pointer of one type to address of a variable of another type.

• It is also invalid to assign a pointer of one type to pointer of another type.

Sample Code 11: Pointer Dereferencing Incompatibility

7
Programming for problem solving unit 4 Notes

Pointers Arithmetic Operations in C


Pointer variables are used to store the address of variables. Address of any variable is an

unsigned integer value i.e., it is a numerical value. So we can perform arithmetic operations on

pointer values. But when we perform arithmetic operations on pointer variable, the result

depends on the amount of memory required by the variable to which the pointer is pointing.

In the c programming language, we can perform the following arithmetic operations on

pointers...

✓ Increment and decrement of a pointer


✓ Addition of integer to a pointer
✓ Substraction of integer to a pointer.
✓ Subtraction of two pointers

Increment and decrement of a pointer


Increment: It is a condition that also comes under addition. When a pointer is
incremented, it actually increments by the number equal to the size of the data
type for which it is a pointer.
ForExample:
If an integer pointer that stores address 1000 is incremented, then it will
increment by 4(size of an int), and the new address will point to 1004. While if
a float type pointer is incremented then it will increment by 4(size of a float)
and the new address will be 1004.
Decrement: It is a condition that also comes under subtraction. When a pointer
is decremented, it actually decrements by the number equal to the size of the
data type for which it is a pointer.
For Example:
If an integer pointer that stores address 1000 is decremented, then it will
decrement by 4(size of an int), and the new address will point to 996. While if
a float type pointer is decremented then it will decrement by 4(size of a float)
and the new address will be 996.

8
Programming for problem solving unit 4 Notes

Example of Pointer Increment and Decrement

int main()
{
int a = 22;
int *p = &a;
printf("p = %u\n", p); // p = 6422288
p++;
printf("p++ = %u\n", p); //p++ = 6422292 +4 // 4 bytes
p--;
printf("p-- = %u\n", p); //p-- = 6422288 -4 // restored to original value

float b = 22.22;
float *q = &b;
printf("q = %u\n", q); //q = 6422284
q++;
printf("q++ = %u\n", q); //q++ = 6422288 +4 // 4 bytes
q--;
printf("q-- = %u\n", q); //q-- = 6422284 -4 // restored to original value

char c = 'a';
char *r = &c;
printf("r = %u\n", r); //r = 6422283
r++;
printf("r++ = %u\n", r); //r++ = 6422284 +1 // 1 byte
r--;
printf("r-- = %u\n", r); //r-- = 6422283 -1 // restored to original value

return 0;
}
Output:
p = 1441900792

9
Programming for problem solving unit 4 Notes

p++ = 1441900796
p-- = 1441900792
q = 1441900796
q++ = 1441900800
q-- = 1441900796
r = 1441900791
r++ = 1441900792
r-- = 1441900791
2. Addition of Integer to Pointer
When a pointer is added with an integer value, the value is first multiplied by the size of the
data type and then added to the pointer.
For Example:
Consider the same example as above where the ptr is an integer pointer that stores 1000 as an
address. If we add integer 5 to it using the expression, ptr = ptr + 5, then, the final address
stored in the ptr will be ptr = 1000 + sizeof(int) * 5 = 1020.

Example of Addition of Integer to Pointer

// C program to illustrate pointer Addition

#include <stdio.h>

// Driver Code

int main()

// Integer variable

int N = 4;

10
Programming for problem solving unit 4 Notes

// Pointer to an integer

int *ptr1, *ptr2;

// Pointer stores the address of N

ptr1 = &N;

ptr2 = &N;

printf("Pointer ptr2 before Addition: ");

printf("%p \n", ptr2);

// Addition of 3 to ptr2

ptr2 = ptr2 + 3;

printf("Pointer ptr2 after Addition: ");

printf("%p \n", ptr2);

return 0;

Output
Pointer ptr2 before Addition: 0x7ffca373da9c
Pointer ptr2 after Addition: 0x7ffca373daa8
3. Subtraction of Integer to Pointer
When a pointer is subtracted with an integer value, the value is first multiplied by the size of
the data type and then subtracted from the pointer similar to addition.
For Example:
Consider the same example as above where the ptr is an integer pointer that stores 1000 as an
address. If we subtract integer 5 from it using the expression, ptr = ptr – 5, then, the final
address stored in the ptr will be ptr = 1000 – sizeof(int) * 5 = 980.
Example of Subtraction of Integer from Pointer

Below is the program to illustrate pointer Subtraction:


C

// C program to illustrate pointer Subtraction

#include <stdio.h>

11
Programming for problem solving unit 4 Notes

// Driver Code

int main()

// Integer variable

int N = 4;

// Pointer to an integer

int *ptr1, *ptr2;

// Pointer stores the address of N

ptr1 = &N;

ptr2 = &N;

printf("Pointer ptr2 before Subtraction: ");

printf("%p \n", ptr2);

// Subtraction of 3 to ptr2

ptr2 = ptr2 - 3;

printf("Pointer ptr2 after Subtraction: ");

printf("%p \n", ptr2);

return 0;

Output
Pointer ptr2 before Subtraction: 0x7ffd718ffebc
Pointer ptr2 after Subtraction: 0x7ffd718ffeb0
4. Subtraction of Two Pointers
The subtraction of two pointers is possible only when they have the same data type. The result
is generated by calculating the difference between the addresses of the two pointers and
calculating how many bits of data it is according to the pointer data type. The subtraction of
two pointers gives the increments between the two pointers.
ForExample:
Two integer pointers say ptr1(address:1000) and ptr2(address:1004) are
12
Programming for problem solving unit 4 Notes

subtracted. The difference between addresses is 4 bytes. Since the size of int is 4 bytes,
therefore the increment between ptr1 and ptr2 is given by (4/4) = 1.

Example of Subtraction of Two Pointer

Below is the implementation to illustrate the Subtraction of Two Pointers:

// C program to illustrate Subtraction

// of two pointers

#include <stdio.h>

// Driver Code

int main()

int x = 6; // Integer variable declaration

int N = 4;

// Pointer declaration

int *ptr1, *ptr2;

ptr1 = &N; // stores address of N

ptr2 = &x; // stores address of x

printf(" ptr1 = %u, ptr2 = %u\n", ptr1, ptr2);

// %p gives an hexa-decimal value,

// We convert it into an unsigned int value by using %u

// Subtraction of ptr2 and ptr1

x = ptr1 - ptr2;

// Print x to get the Increment

// between ptr1 and ptr2

printf("Subtraction of ptr1 "

"& ptr2 is %d\n",

13
Programming for problem solving unit 4 Notes

x);

return 0;

Output
ptr1 = 2715594428, ptr2 = 2715594424
Subtraction of ptr1 & ptr2 is 1
5. Comparison of Pointers
We can compare the two pointers by using the comparison operators in C. We can implement
this by using all operators in C >, >=, <, <=, ==, !=. It returns true for the valid condition and
returns false for the unsatisfied condition.
1. Step 1: Initialize the integer values and point these integer values to the pointer.
2. Step 2: Now, check the condition by using comparison or relational operators on
pointer variables.
3. Step 3: Display the output.

Example of Pointer Comparision

// C Program to illustrare pointer comparision

#include <stdio.h>

int main()

// declaring array

int arr[5];

// declaring pointer to array name

int* ptr1 = &arr;

// declaring pointer to first element

int* ptr2 = &arr[0];

if (ptr1 == ptr2) {

14
Programming for problem solving unit 4 Notes

printf("Pointer to Array Name and First Element "

"are Equal.");

else {

printf("Pointer to Array Name and First Element "

"are not Equal.");

return 0;

Output
Pointer to Array Name and First Element are Equal.
Pointers and arrays

In the c programming language, when we declare an array the compiler allocate the required
amount of memory and also creates a constant pointer with array name and stores the base
address of that pointer in it. The address of the first element of an array is called as base
address of that array.

The array name itself acts as a pointer to the first element of that array. Consider the following
example of array declaration...
Example Code
int marks[6] ;
For the above declaration, the compiler allocates 12 bytes of memory and the address of first
memory location (i.e., marks[0]) is stored in a constant pointer called marks. That means in the
above example, marks is a pointer to marks[0].
Example Program
#include<stdio.h>
#include<conio.h>

int main()
{
int marks[6] = {89, 45, 58, 72, 90, 93} ;
15
Programming for problem solving unit 4 Notes

int *ptr ;
ptr = marks ;
printf(“Base Address of 'marks' array = %u\n”, ptr) ;
return 0;
}

Output:

MOST IMPORTANT POINTS TO BE REMEMBERED


1. An array name is a constant pointer.

2. We can use the array name to access the address and value of all the elements of
that array.

3. Since array name is a constant pointer we can't modify its value.

Consider the following example statements...

Example Code

ptr = marks + 2 ;

Here, the pointer variable "ptr" is assigned with address of "marks[2]" element.

Example Code

printf("Address of 'marks[4]' = %u", marks+4) ;

The above printf statement displays the address of element "marks[4]".

Example Code

printf("Value of 'marks[0]' = %d", *marks) ;

printf("Value of 'marks[3]' = %d", *(marks+3)) ;

In the above two statements, first printf statement prints the value 89 (i.e., value of marks[0]) and
the second printf statement prints the value 72 (i.e., value of marks[3]).

16
Programming for problem solving unit 4 Notes

Example Code

marks++ ;

The above statement generates compilation error because the array name acts as a constant
pointer. So we can't change its value.

In the above example program, the array name marks can be used as follows...

marks is same as &marks[0]


marks + 1 is same as &marks[1]
marks + 2 is same as &marks[2]
marks + 3 is same as &marks[3]
marks + 4 is same as &marks[4]
marks + 5 is same as &marks[5]
*marks is same as marks[0]
*(marks + 1) is same as marks[1]
*(marks + 2) is same as marks[2]
*(marks + 3) is same as marks[3]
*(marks + 4) is same as marks[4]
*(marks + 5) is same as marks[5]

Example program Display the elements of an array in reverse order using pointers

#include<stdio.h>
#define N 5
int main()
{
int a[N], i, *ptr;
printf("Enter %d integer numbers\n", N);
for(i = 0; i < N; i++)
scanf("%d", &a[i]);
ptr = &a[N - 1];
printf("\nElements of array in reverse order ...\n");
for(i = 0; i < N; i++)
printf("%d\n", *ptr--);
return 0;
}
Find the biggest and smallest elements of an array using pointer to an array

#include<stdio.h>
#define N 5
int main()
{

17
Programming for problem solving unit 4 Notes

int a[N], i, *small;


printf("Enter %d integer numbers\n", N);
for(i = 0; i < N; i++)
scanf("%d", &a[i]);
small = &a[0];
for(i = 1; i < N; i++)
{
if( *(a + i) < *small)
*small = *(a + i);
}
printf("Smallest Element In The Array: %d\n", *small);
return 0;
}
Pointers and functions
Passing the pointers to the function means the memory location of the variables is passed to the
parameters in the function, and then the operations are performed. The function definition
accepts these addresses using pointers, addresses are stored using pointers.
Arguments Passing without pointer
When we pass arguments without pointers the changes made by the function would be done to
the local variables of the function.
Below is the C program to pass arguments to function without a pointer:
// C program to swap two values
// without passing pointer to
// swap function.
#include <stdio.h>

void swap(int* a, int* b)


{
int temp;
temp = *a;
*a = *b;
*b = temp;
}

// Driver code
int main()
{
int a = 10, b = 20;
printf("Values before swap function are: %d, %d\n",
a, b);
swap(&a, &b);
printf("Values after swap function are: %d, %d",
a, b);
18
Programming for problem solving unit 4 Notes

return 0;
}

Structures: Structure definition

The structure in C is a user-defined data type that can be used to group items of possibly
different types into a single type. The struct keyword is used to define the structure in the C
programming language. The items in the structure are called its member and they can be of
any valid data type.

C Structure Declaration
We have to declare structure in C before using it in our program. In structure declaration, we
specify its member variables along with their datatype. We can use the struct keyword to
declare the structure in C using the following syntax:

Syntax

struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};
The above syntax is also called a structure template or structure prototype and no memory is
allocated to the structure in the declaration.
C Structure Definition
To use structure in our program, we have to define its instance. We can do that by creating
variables of the structure type. We can define structure variables using two methods:

1. Structure Variable Declaration with Structure Template

struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
}variable1, varaible2, ...;

Example:Method 1 variable declaration

Struct Employee
{
int empno; //2 bytes
char ename[20]; //20 bytes
19
Programming for problem solving unit 4 Notes

float empsal; // 4 bytes


}e1,e2,e3;

Total 26 bytes of memory will be allocated for a astructure.


Example:Method 2 variable declaration

int main()
{
Struct Employee e1,e2,e3;
}
Access Structure Members
➢ We can access structure members by using the ( . ) dot operator.

Syntax

structure_name.member1;
structure _name.member2;
In the case where we have a pointer to the structure, we can also use the arrow operator to
access the members.

Example:
e1.empno;
e1.ename;
e1.salary
Initialize Structure Members
Structure members cannot be initialized with the declaration. For example, the following C
program fails in the compilation.
struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};
Example1 Program:WAP to display the size of structure and to display the employee details

#include<stdio.h>

Struct Employee
{
int empno; //2 bytes
char ename[20]; //20 bytes
float empsal; // 4 bytes
20
Programming for problem solving unit 4 Notes

};
Void main()

Struct Employee e={101,”Hari”,40000);

Printf(“\n The size of the structure=%d”,sizeof(e));

Printf(“\n The size of the structure=%d”,sizeof(struct Employee));

Printf(“\n The employee details are…”);

Printf(“Employee number=%d”,e.empno);

Printf(“Employee number=%s”,e.ename);

Printf(“Employee number=%d”,e.salary);

Example 2:

WAP to store and display the student details

#include<stdio.h>

Struct student
{
char name[40];
int roll;
float marks;
}s;
Void main()

Printf(“\n Enter the information”);

Printf(“\n Enter the name:”);

Strcpy(s.name,”Matrusri”);

S.roll=100;

s.marks=25;

Printf(“Details of the student are……. “);

Printf(“ Nameof the student =%s\n”,s.name);


21
Programming for problem solving unit 4 Notes

Printf(“Rollnumber=%d”,s,roll );

Printf(“Marks=%f”, s.marks);

Example 3: To store N students’ details (name, roll no, subject1, subject2, subject3 marks),
compute average_marks, and display the grade of each student.

#include<stdio.h>

Struct student

char name[20];

int rollno;

float subject1,subject2,subject3;

float avg;

float tot;

};

int main()

struct student s1;

printf(“enter the student information”);

printf(“enter the student name”);

scanf(“%s”,&s1.name);

printf(“enter the rollnumber”);

scanf(“%d”,s1.rollno);

printf(“enter the subject1,subject2,subject3 marks”);

scanf(“%f”,&s1.subject1, &s1.subject2, &s1.subject3);

s1.tot=(s1.subject1+s1.subject2+s1.subject3);

s1.avg=(s1.tot)/3;
22
Programming for problem solving unit 4 Notes

printf(“Total=%f,Average=%f”,s1.tot,s1.avg);

if(s1.avg>=75)

printf(“Grade A”);

else if((s1.avg>65 && (s1.avg <75))

printf(“Grade B”);

else if(((s1.avg<65 && (s1.avg >50))

printf(“Grade C”);

else

printf(“Fail”);

return 0;

ARRAY OF STRUCTURES IN C:

An array of structures is a way of storing multiple data items of the same type in a single
variable. Each data item is called an element of the array, and each element has one or more
fields that store different kinds of information. For example, you can use an array of structures to
store the details of several employees, such as their name, ID, and attendance.

To declare an array of structures, you need to first define the structure type, and then specify the
array name and size. For example:

// Define the structure type

struct Employee {

char Name[20];

int employeeID;

int WeekAttendance[7];

};

// Declare an array of structures

struct Employee emp[5];

This declares an array of structures called emp, which can store up to 5 elements of type struct
Employee. Each element has three fields: Name, employeeID, and WeekAttendance.
23
Programming for problem solving unit 4 Notes

To initialize an array of structures, you can use curly braces to assign values to each element and
field. For example:

// Initialize an array of structures


struct Employee emp[5] =
{
{"Alice", 101, {1, 1, 1, 1, 1, 0, 0}},
{"Bob", 102, {1, 0, 1, 0, 1, 0, 0}},
{"Charlie", 103, {1, 1, 1, 1, 0, 0, 0}},
{"David", 104, {1, 0, 0, 0, 0, 0, 0}},
{"Eve", 105, {1, 1, 1, 1, 1, 1, 1}}
};

This initializes the array of structures with 5 elements, each with a name, an ID, and a 7-element
array of integers representing the attendance for each day of the week.
To access an element or a field of an array of structures, you can use the array index and the dot
operator. For example:
// Access an element of an array of structures
printf("Employee Name: %s\n", emp[0].Name); // Prints Alice

// Access a field of an element of an array of structures


printf("Employee ID: %d\n", emp[0].employeeID); // Prints 101

// Access an array within a field of an element of an array of structures


printf("Employee Attendance on Monday: %d\n", emp[0].WeekAttendance[0]); //
Prints 1
/*PROGRAM TO ILLUSTRATE ABOUT ARRAY OF STRUCTURES*/

#include<stdio.h>

struct student

char id[10];

char name[15];

int m1;

int m2;

int tot;

};

void main()

{
24
Programming for problem solving unit 4 Notes

struct student s[3];

int i;

for(i=0;i<3;i++)

printf("\n\nEnter student details for s[%d]",i);

printf("\n\nID NAME MARKS1(int) MARKS2(int)\n\n");

scanf("%s%s%d%d",s[i].id, s[i].name, &s[i].m1, &s[i].m2);

s[i].tot = s[i].m1 + s[i].m2;

printf("\n\nFrom Structure variable s[%d]:",i);

printf("\n\n Hello %s! Your Total marks are: %d",s[i].name,s[i].tot);

printf("\n\n");

Example 2:WAP to display the employee details using arrays and structures

#include<stdio.h>

struct employee

int empno;

char ename[20];

float salary;

};

void main()

struct employee e[3];

int i;

25
Programming for problem solving unit 4 Notes

for (i=0;i<3;i++)

printf(“\n enter number,name,salry for employee %d”,i+1);

scanf(‘%d%s%f”,&e[i].empno,&e[i].ename,&e[i].salary);

printf(“employee details are…”);

printf(“\n\n number \t\t name \t\t salary “);

for(i=0;i<3;i++)

printf(“\n\n %d \t\t %s \t\t\t %f”,e[i].empno,e[i].ename,e[i].salary);

Nested structures

A structure with in a structure is called as “Nested Structure”.

Nested structures are used to group some of the members of a structure.

Syntax:
struct name_1
{
member1;
member2;
.
.
member n;
struct name_2

member_1;

member_2;

.
26
Programming for problem solving unit 4 Notes

member_n;

}, var1

} var2;

Accessing the nested structure variables

outer structure variable.inner structure variable.member;

different ways of nesting structure


the structure can be nested in the following different ways:
1. by separate nested structure
2. by embedded nested structure.
1. by separate nested structure: in this method, the two structures are created, below is
the c program to implement the approach:
Example:
#include<stdio.h>
struct dob
{
int day;
int mm,yy;
};
struct student
{
int id;
char name[20];
struct dob d;
};
int main()
{
Struct student s;
Printf(“ enter the student ID”);
scanf(“%d”,&s.id);
printf(“enter the student name:”);
scanf(“%s”,&s,name);
printf(“enter the date of birth:”);
scanf(“%d%d%d”,&s.d.day,&s.d.mm,&s.d.yy);
printf(“\n student details are:”);
printf(“\n student id=%d”,s.id);
printf(“\n student name=%s”,s.name);
printf(“ student date of birth=%d-%d-%d”,s.d.day,s.d.mm,s.d.yy);
return 0;
}

27
Programming for problem solving unit 4 Notes

2.Embedded Nested structure

struct student

int id;

char name[20];

struct dob

int day,mm,yy;

}d;

};

int main()
{
Struct student s;
Printf(“ enter the student ID”);
scanf(“%d”,&s.id);
printf(“enter the student name:”);
scanf(“%s”,&s,name);
printf(“enter the date of birth:”);
scanf(“%d%d%d”,&s.d.day,&s.d.mm,&s.d.yy);
printf(“\n student details are:”);
printf(“\n student id=%d”,s.id);
printf(“\n student name=%s”,s.name);
printf(“ student date of birth=%d-%d-%d”,s.d.day,s.d.mm,s.d.yy);
return 0;
}

Passing structure to functions


We can pass a structure to function in 3 ways

➢ Passing individual member of a structure


➢ Passing entire structure
➢ Passing the address of a structure (pointers)

Passing individual member of a structure:

➢ We can pass each member of a structure individually to a structure

28
Programming for problem solving unit 4 Notes

➢ In the function these values of members will be stored in ordinary variables


➢ The problem in this type is if structure contains more no of members, then it will be
difficult to pass each member separately in to a function.

/*SENDING INDIVIDUAL ELEMENTS OF A STRUCTURE TO A FUNCTION*/

#include<stdio.h>

struct student

}s;

char id[10];

char name[20];

float m;

show(char[],char[],float);

void main()

clrscr();

printf("\nEnter id:");

gets(s.id);

printf("\nEnter Name: ");

gets(s.name);

printf("\nEnter Marks: ");

scanf("%f",&s.m);

show(s.id,s.name,s.m);

getch();

show(char sid[10],char sname[20],float score)

29
Programming for problem solving unit 4 Notes

printf("\nYour details are \n\n ID \t NAME \t MARKS \n\n");

printf(" %s %s %f",sid,sname,score);

O/P:

printf("\nYour details are \n\n ID \t NAME \t MARKS \n\n");

printf(" %s %s %f",sid,sname,score);

Enter id: A100

Enter Name: RAJ

Enter Marks: 89.77

Your details are

ID NAME MARKS

A100 RAJ 89.769997

2.Passing an entire array to the structure:

Instead of passing individual members we can pass the entire structure to a function

/*SENDING WHOLE STRUCTURE VARIABLE TO A FUNCTION*/


#include<stdio.h>

struct student

char id[10];

char name[20];

float m;

}s;

void main()

printf("\nEnter id:");

30
Programming for problem solving unit 4 Notes

gets(s.id);

printf("\nEnter Name: ");

gets(s.name);

printf("\nEnter Marks: ");

scanf("%f",&s.m);

show(s);

getch();

show(struct student p)

printf("\nYour details are \n\n ID \t NAME \t MARKS \n\n");

printf(" %s \t %s \t %f",p.id,p.name,p.m);

3.Passing the address of a structure instead of variables:

➢ To avoid duplicate copies of structures we pass the address of a structure instead of


values.
➢ To receive the address the formal arguments must be declared as pointers

/*SENDING THE ADDRESS OF A STRUCTURE VARIABLE TO A FUNCTION*/

#include<stdio.h>

struct student

char id[10];

char name[20];

float m;

}s;

void main()

31
Programming for problem solving unit 4 Notes

printf("\nEnter id:");

gets(s.id);

printf("\nEnter Name: ");

gets(s.name);

printf("\nEnter Marks: ");

scanf("%f",&s.m);

show(&s);

getch();

show(struct student *p)

printf("\nYour details are \n\n ID \t NAME \t MARKS \n\n");

printf(" %s \t %s \t %f",p->id,p->name,p->m);

O/P:

Enter id:Mahi

Enter Name: A103

Enter Marks: 79.89

Your details are

ID NAME MARKS

Mahi A103 79.889999

Pointers and structures


A structure pointer is defined as the pointer which points to the address of the memory block
that stores a structure known as the structure pointer. Complex data structures like Linked lists,

32
Programming for problem solving unit 4 Notes

trees, graphs, etc. are created with the help of structure pointers. The structure pointer tells the
address of a structure in memory by pointing the variable to the structure variable.

Syntax:

Struct structure name *var;

Ex:struct student *ptr;

Struct student s;

Ptr=&s;

C program to demonstrate structure pointer


#include <stdio.h>

struct point
{
int value;
};

int main()
{

struct point s;

// Initialization of the structure pointer


struct point* ptr = &s;

return 0;
}

Accessing the structure members

Accessing the Structure Member with the Help of Pointers

There are two ways to access the members of the structure with the help of a
structure pointer:
1. With the help of (*) asterisk or indirection operator and (.) dot
operator.
2. With the help of ( -> ) Arrow operator.

33
Programming for problem solving unit 4 Notes

Below is the program to access the structure members using the structure
pointer with the help of the dot operator.
// C Program to demonstrate Structure pointer

#include <stdio.h>

#include <string.h>

struct Student {

int roll_no;

char name[30];

char branch[40];

int batch;

};

int main()

struct Student s1;

struct Student* ptr = &s1;

s1.roll_no = 27;

strcpy(s1.name, "Kamlesh Joshi");

strcpy(s1.branch, "Computer Science And Engineering");

s1.batch = 2019;

printf("Roll Number: %d\n", (*ptr).roll_no);

printf("Name: %s\n", (*ptr).name);

printf("Branch: %s\n", (*ptr).branch);

printf("Batch: %d", (*ptr).batch);

return 0;

34
Programming for problem solving unit 4 Notes

Below is the program to access the structure members using the structure pointer with the help
of the Arrow operator. In this program, we have created a Structure Student containing
structure variable s. The Structure Student has roll_no, name, branch, and batch.

WAP a C Program to demonstrate Structure pointer


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

// Creating Structure Student


struct Student
{
int roll_no;
char name[30];
char branch[40];
int batch;
};

// variable of structure with pointer defined


struct Student s, *ptr;

int main()
{

ptr = &s;
printf("Enter the Roll Number of Student\n");
scanf("%d", &ptr->roll_no);
printf("Enter Name of Student\n");
scanf("%s", &ptr->name);
printf("Enter Branch of Student\n");
scanf("%s", &ptr->branch);
printf("Enter batch of Student\n");
scanf("%d", &ptr->batch);

// Displaying details of the student


printf("\nStudent details are: \n");

printf("Roll No: %d\n", ptr->roll_no);


printf("Name: %s\n", ptr->name);
printf("Branch: %s\n", ptr->branch);
printf("Batch: %d\n", ptr->batch);

return 0;
}

35
Programming for problem solving unit 4 Notes

Self-referential structures
A structure which contains a member that points to the same structure type is called “self
referential structure”.

Self-referential structures are used in data structures like “linked list”.

Example:

Struct self

Int p;

Struct self *ptr;

};

Example Program to illustrate self referential structures

Struct code

Int I;

Char c;

Struct code *ptr;

};

Int main()

struct code var1;

struct code var2;

var1.i=65;

var1.c=’h’;

var1.ptr=null;

var2.i=75;

var2.c=’j’;
36
Programming for problem solving unit 4 Notes

var2.ptr=null;

var1.ptr=&var2;

printf(“%d%c”,var1.ptr->i,var1.ptr->c)

65 H 2000 75 J NULL
NULL

Var1.ptr=&var 2

Ouput:

75 J

Unions in C Programming Language:


➢ Union is a collection of elements of different datatypes.
➢ The difference between structures and unions will be in terms of storage.
➢ Each member of a structure has its own memory location, whereas all the members of the
union share the same memory location.

/*PROGRAM TO ILLUSTRATE ABOUT UNION*/

#include<stdio.h>
37
Programming for problem solving unit 4 Notes

union student

char name[15];

int m1;

float m2;

};

void main()

union student u; clrscr();

strcpy(u.name,"Raj");

printf("\nHello %s",u.name);

u.m1=88;

printf("\nMarks1= %d",u.m1);

u.m2=96.57;

printf("\nMarks2= %f",u.m2);

/*if we assign all at once as follows observe the output... No need to write the below code in the

strcpy(u.name, "Ravi");

u.m1=88;

u.m2=96.57;

printf("\n\n\n Hello %s\n Marks1=%d \n Marks2= %f", u.name, u.m1,u.m2);

getch();

Output:

Hello Raj

Marks1= 88

38
Programming for problem solving unit 4 Notes

Marks2= 96.570000

Hello #?$) @ /*Garbage*/

Marks1=9175 /*Garbage*/

Marks2= 96.570000 /*Last entry will be Correct

Example : C program to find the size of the union

#include <stdio.h>
union test1
{
int x;
int y;
} Test1;

union test2
{
int x;
char y;
} Test2;

union test3
{
int arr[10];
char y;
} Test3;

// driver code
int main()
{
// finding size using sizeof() operator
int size1 = sizeof(Test1);
int size2 = sizeof(Test2);
int size3 = sizeof(Test3);

printf("Sizeof test1: %d\n", size1);


printf("Sizeof test2: %d\n", size2);
printf("Sizeof test3: %d", size3);
return 0;
}
Difference between C Structure and C Union
The following table lists the key difference between the structure and union in C:

39
Programming for problem solving unit 4 Notes

Structure Union

The size of the structure is equal to or greater The size of the union is the size
than the total size of all of its members. of its largest member.

The structure can contain data in multiple Only one member can contain
members at the same time. data at the same time.

It is declared using the union


It is declared using the struct keyword.
keyword.

Enumerated data types:

Enumeration or Enum in C is a special kind of data type defined by the user. It consists of
constant integrals or integers that are given names by a user. The use of enum in C to name the
integer values makes the entire program easy to learn, understand, and maintain by the same or
even different programmer.

enum week{Mon, Tue, Wed};


enum week day;

// Or

enum week{Mon, Tue, Wed}day;

Example Program1

#include<stdio.h>

enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};

int main()

{
enum week day;
day = Wed;

40
Programming for problem solving unit 4 Notes

printf("%d",day);
return 0;
}
Output:

Example Program2

#include<stdio.h>

enum year{Jan, Feb, Mar, Apr, May, Jun, Jul,


Aug, Sep, Oct, Nov, Dec};

int main()
{
int i;
for (i=Jan; i<=Dec; i++)
printf("%d ", i);

return 0;
}
Output:
0 1 2 3 4 5 6 7 8 9 10 11

Interesting facts about initialization of enum.


1. Two enum names can have same value. For example, in the following C program both
‘Failed’ and ‘Freezed’ have same value 0.

#include <stdio.h>
enum State {Working = 1, Failed = 0, Freezed = 0};

int main()
{
printf("%d, %d, %d", Working, Failed, Freezed);
return 0;
}

Output:
1, 0, 0
2. If we do not explicitly assign values to enum names, the compiler by default assigns values
starting from 0. For example, in the following C program, sunday gets value 0, monday gets 1,
and so on.

41
Programming for problem solving unit 4 Notes

#include <stdio.h>
enum day {sunday, monday, tuesday, wednesday, thursday, friday, saturday};

int main()
{
enum day d = thursday;
printf("The day number stored in d is %d", d);
return 0;
}

Output:
The day number stored in d is 4
3. We can assign values to some name in any order. All unassigned names get
value as value of previous name plus one.

#include <stdio.h>
enum day {sunday = 1, monday, tuesday = 5,
wednesday, thursday = 10, friday, saturday};

int main()
{
printf("%d %d %d %d %d %d %d", sunday, monday, tuesday,
wednesday, thursday, friday, saturday);
return 0;
}

Output:
1 2 5 6 10 11 12
4. The value assigned to enum names must be some integral constant, i.e., the value must be in
range from minimum possible integer value to maximum possible integer value.
5. All enum constants must be unique in their scope. For example, the following program fails
in compilation.

enum state {working, failed};


enum result {failed, passed};

int main() { return 0; }

Output:
Compile Error: 'failed' has a previous declaration as 'state failed'
42
Programming for problem solving unit 4 Notes

Important Questions:

1. Write a C program to illustrate the concept of structure with in structure?


2. With proper examples explain different arithmetic operations on pointers.?
3. Explain Self Referential structure with C program.?
4. Define Structure give example. Mention different ways to access the members of
structure with examples?
5. What is Structure? Demonstrate with an example program?
6. What is a pointer? How it is used in self-referential structures?

43

You might also like