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

Unit 4-1

Uploaded by

elitetube1
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)
30 views

Unit 4-1

Uploaded by

elitetube1
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/ 34

UNIT IV STRUCTURE AND POINTERS 09

Structure Introduction – Structure definition – Structure declaration


– Structure within a structure –Self Referential Structure. Pointers -
Definition – Initialization – Pointers arithmetic – Pointers and arrays -
Pointer to Function –Pointer and Structure- Simple programs.

Text Books
1. Balagurusamy. E, ―Programming in ANSI C, Tata McGraw Hill, 8thEdition,2019.
2. YashvantKanetkar, ―Let us C‖, BPB Publications, 16th Edition, 2017
3. Herbert Schildt,‖ C: The Complete Reference‖, McGraw Hill, FourthEdition,2014
Reference Books

1. Vikas B. Agarwal Jyoti P. Mirani, ―Computer Fundamentals , Nirali Prakashan Aug-2019,


2. Ashok N Kamthane, ―Computer Programming‖, Pearson education, Second Impression,2012.
3. VikasVerma, ―A Workbook on C ―, Cengage Learning, Second Edition,2012.
4. P.Visu, R.Srinivasan and S.Koteeswaran, ―Fundamentals of Computing and Programming‖, Fourth Edition, Sri
Krishna Publications, 2012.
5. PradipDev, ManasGhoush, ―Programming in C‖, Second Edition, Oxford University Press, 2011.
Introduction
In C language, arrays can store many values of similar types. Data in the array is of the same
composition in nature as far as the type is concerned.
In real life, we need to have different data types;
for example to maintain telephone directory we should have the information such as name,
number and so on. Name of the person in ‘char’ data type and telephone number is an ‘int’ data type.
All these cannot be expressed in the single array. Hence array cannot be used. In order to overcome
this, a special feature is provided in C known as structure.

Structure
A structure is a collection of one or more variables of different data types, grouped together under
a single name. It is derived data type to be arranged in a group of related data items of different data
types. It is a user defined data type because user can decide the data types to be included in the structure
body. By using structures we can make a group of variables, arrays and pointers. Moreover, it is a
convenient tool for handling a group of logically related data items.
Difference between Array and Structure

Array Structure

Array is a collection of same Structure is a collection of


data type elements different data type elements
An array is derived data type Structure is a programmer
defined one
Array elements are accessed Structure elements are
by their position or subscript accessed by their object as ‘.’
operator
Array elements are referred Structure elements are
by subscript referred by their unique name
Does not have bit field May contain bit field

It is not a keyword It is a keyword


Declaration of structure variable
Rules
syntax -A structure must end with a semicolon
-usually a structure appears at the top of the source program
struct struct_name
-Each structure must be terminated
{ -The structure variable must be accessed with structure variable
datatype variable 1; and the member is established using a dot operator(.) otherwise
datatype variable 2; called as period operator.
};
//You can then declare a variable of this derived data type as −
struct struct_name s1,s2,….sn;

It includes the following

 The keyword struct


 structure tag name
 list of variable names separated by commas
 A terminating semicolon
 s1,s2,…sn are structure variables
#include <stdio.h>
struct book
{
char title[10]; OUTPUT
double price; Title: Learn C
int pages; Price: 675.500000
No of Pages: 325
};
int main ()
{
struct book b1 = {"Learn C", 675.50, 325};
printf("Title: %s\n", b1.title);
printf("Price: %lf\n", b1.price);
printf("No of Pages: %d\n", b1.pages);
return 0;
}
#include <stdio.h>
#include <string.h>
struct book
{
char title[10];
double price;
int pages;
} b1;
int main ()
{
strcpy(b1.title, "Learn C");
b1.price = 675.50;
b1.pages = 325;
printf("Title: %s\n", b1.title);
printf("Price: %lf\n", b1.price);
printf("No of Pages: %d\n", b1.pages);
return 0;
}
//Program to print the name and phone number using structure
#include<stdio.h>
struct telephone
{
char *name; Output
Name:Jane Doe
int number; Telephonenumber:12345
};
int main()
{
struct telephone index;
index.name=“Jane Doe”;
index. number=12345;
printf(“name:%s\n”,index.name);
printf(“Telephone number:%d\n”,index.number);
return 0;
}
Array of Structure
An array of structures contains data elements of every structure variable stored into an array.
An array of structures is one of the interesting topics for C programmer because it has two powerful data
types namely Structure and Array. Array structure can be declared as follows.
Syntax
struct student
{
char name[20];
int age;
int mark;
}s[3];
In above example s[3] is an array of three elements containing three objects of student structure.Each element of s[3] has structure of student with three members that are name,age and marks.
//Program to print student mark list record using structure
#include<stdio.h>
#include<conio.h> elseif(a[i].avg<80)
struct stud a[i].grade=‘B’;
{ else
int rollno; a[i].grade=‘A’;
char name[30]; }
int mark1,mark2,mark3,total; printf("student mark details:\n");
float avg; printf("\n rollno \t name \t mark1 \t mark2 \t mark3 \t total \t average \t grade");
char grade; for(i=0;i<n;i++)
}a[25]; printf("\n %d\t %s\t %d \t %d \t %f \t %c",a[i].rollno,a[i].name,a[i].mark1,a[i].mark2,a[i].mark3,a[i].total,a[i].avg,
void main(){ a[i].grade);
int i,n; }
clrscr(); Output
printf(“Enter the number of students”); Enter the number of students:2
scanf(“%d”,&n); Enter the student1 details:
for (i=0;i<n;i++) rollno:101
{ Name:jai
printf(“Enter the students %d details:”,i+1); mark1:89
printf(“\n rollno”); mark2:90
scanf(“%d”,&a[i].rollno); mark3:80
printf(“\nName”); Enter the student 2 details:
scanf(“%s”,a[i].name); rollno:102
printf(“\nMark1”); name:raj
scanf(“%d”,&a[i].mark1); mark1:87
printf(“\n Mark2”); mark2:90
scanf(“%d”,&a[i].mark2); mark3:67
printf(“\n Mark3”); Student mark details
scanf(“%d”,&a[i].mark3); rollno name mark1 mark2 mark3 total avg grade
a[i].total=a[i].mark1+a[i].mark2+a[i].mark3; 101 jai 89 90 80 259 86.33 A
a[i].avg=a[i].total/3; 102 raj 87 90 67 244 81.00 A
if(a[i].avg<40)
a[i].grade=‘D’;
else if(a[i].avg<60)
a[i].grade=‘C’
Nested structure
If a structure contains more than one structure as its members, it is known as a nested
structure(i.e) structure within a structure.
#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
void main()
{
struct employee emp;
printf("Enter employee information?\n");
scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin,emp.add.phone);printf("Printing the employ
ee information....\n");
printf("name: %s\nCity: %s\nPincode: %d\nPhone: %s",emp.name,emp.add.city,emp.add.pin,emp.add.pho
ne);
}
Output
Enter employee information?
Arun
Printing the employee information....
Delhi name: Arun
110001 City: Delhi
1234567890 Pincode: 110001
Phone: 1234567890
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, but the dependent
structure(Employee) should be used inside the main structure(Organisation) as a member. Below is the C program
to implement the approach:
2. By Embedded nested structure: Using this method, allows to declare structure inside a structure and it
requires fewer lines of code.
Case 1: Error will occur if the structure is present but the structure variable is missing.
Note:
Whenever an embedded nested structure is created, the variable declaration is compulsory at the end of the
inner structure, which acts as a member of the outer structure. It is compulsory that the structure variable is
created at the end of the inner structure.
Case 2: When the structure variable of the inner structure is declared at the end of the inner structure.
// Driver code
// Declaration of the int main()
// dependent structure {
struct Employee // Structure variable
{ struct Organisation org;

int employee_id; // Print the size of organisation


char name[20]; // structure
int salary; printf("The size of structure organisation : %ld\n",
sizeof(org));
}; Output:
org.emp.employee_id = 101; The size of structure organisation : 68
Organisation Name : XXXXXXXX
// Declaration of the strcpy(org.emp.name, "Robert");
Organisation Number : GFG123768
// Outer structure org.emp.salary = 400000;
Employee id : 101
strcpy(org.organisation_name,
struct Organisation Employee name : Robert
“xxxxxxxx"); Employee Salary : 400000
{ strcpy(org.org_number, "GFG123768");
char organisation_name[20];
char org_number[20]; // Printing the details
printf("Organisation Name : %s\n",
// Dependent structure is used org.organisation_name);
// as a member inside the main printf("Organisation Number : %s\n",
org.org_number);
// structure for implementing printf("Employee id : %d\n",
// nested structure org.emp.employee_id);
struct Employee emp; printf("Employee name : %s\n",
org.emp.name);
}; printf("Employee Salary : %d\n",
org.emp.salary);
}
// C program to implement
// the above approach
#include <stdio.h> Case 1:

// Declaration of the outer


// structure
struct Organisation
{
char organisation_name[20];
char org_number[20];

// Declaration of the employee


// structure
struct Employee
{
int employee_id;
char name[20];
int salary;

// This line will cause error because


// datatype struct Employee is present ,
// but Structure variable is missing.
};
};

// Driver code
int main()
{
// Structure variable of organisation
struct Organisation org;
printf("%ld", sizeof(org));
}
Case 2: // Driver code
int main()
// C program to implement {
// the above approach struct Organisation org;
#include <stdio.h>
#include <string.h> // Print the size of organisation
// structure
printf("The size of structure organisation : %ld\n",
// Declaration of the main sizeof(org));
// structure
struct Organisation org.emp.employee_id = 101;
{ strcpy(org.emp.name, "Robert");
char organisation_name[20]; org.emp.salary = 400000;
char org_number[20]; strcpy(org.organisation_name,“xxxxxxxxx");
strcpy(org.org_number, "GFG123768");
// Printing the details
// Declaration of the dependent printf("Organisation Name : %s\n",
// structure org.organisation_name);
struct Employee printf("Organisation Number : %s\n",
{ org.org_number);
int employee_id; printf("Employee id : %d\n",
char name[20]; org.emp.employee_id);
printf("Employee name : %s\n", Output:
int salary; The size of structure organisation : 68
org.emp.name);
printf("Employee Salary : %d\n", Organisation Name : xxxxxxxx
// variable is created which acts org.emp.salary); Organisation Number : GFG123768
// as member to Organisation structure. } Employee id : 101
Employee name : Robert
} emp; Employee Salary : 400000
};
Passing structure to a function
C language supports the passing of structures to functions as an argument.The general form of syntax for
structures to functions is as given below
Whenever a structure element is required to pass to any function,it is essential to declare the structure
outside the main() function,i.e global.Generally they can perform in three ways.
1.Passing structure members to function
2.Passing entire structures to function
3.Passing structure to a function by address
1.Passing structure members to function
In this each member of the structure is passed as an actual argument of the function call.The method is
not efficient when the structure size is large.
//Program to pass a structure to a function
#include<stdio.h>
struct student
{
int rno;
float perc;
};
main()
{
struct student s1;
printf(“enter rollno”);
scanf(“%d”,&s1.rno);
printf(“enter percentage”);
scnf(“%d”,&s1.perc);
display(s1.rno,s1.perc);
}
display(int a,float b)
{
printf(“Rol no is %d”,a);
printf(“Percentage is %f”,b);
return 0;
}
Output
2.Passing entire structures to a function
In this,the entire copy of the structure is passed to the called function.Since this works only on the copy,any
changes to structure members within the functions will not affect the original structure. This method is not
supported by the compilers.
//Program to return the entire structure to the calling function
#include<stdio.h>
struct student
{
int rno;
float perc;
};
main()
{
struct student s1;
printf(“enter rollno”);
scanf(“%d”,&s1.rno);
printf(“enter percentage”);
scnf(“%d”,&s1.perc);
display(s1);
}
display(struct student s2) //value of s2=s1
{
printf(“Rollno is %d”,s2.rno);
printf(“Percentage is %f”,s2.perc);
return 0;
}
3.Passing Structure to a Function by Address
In this,the whole structure is passed to another function by address. It means only the address of the
structure is passed to another function. The whole structure is not passed to another function with all
members an their values. So, this structure can be accessed from called function by its address. This
method is more efficient compared to the previous method.
#include<stdio.h>
struct student
{
int rno;
float perc;
};
main()
{
struct student s1;
printf(“enter rollno”);
scanf(“%d”,&s1.rno);
printf(“enter percentage”);
scnf(“%d”,&s1.perc);
display(& s1);
}
display(struct student *p)
{
printf(“Rollno is %d”,p->rno);
printf(“Percentage is %f”,p->perc);
return 0;
}
User defined datatype
Enumerated data type
We known that words speak more than numbers(as pictures speak more than words)
For example we may use integers 1,2,3,….12 to represent month for easy programming.
It is more readable and understandable if we replace these numbers by some meaningful and descriptive
names such as Jan,Feb,…..,Dec.
This concept of replacing integers by some descriptive names gives rise to new data type called numerated
type.
An enumerated data type is a user defined data type which can take the integer values from a list.
These integer values are replaced by meaningful and descriptive names so as to enhance the
readability of the program.
These descriptive names are called enumerators or enumerator constants.
Declaring an enumerated data type
To declare an enumerated type,its identifiers and its values must be declared.Because it is derived from
integer type,its operations are the same as for integers.
Syntax
enum type_Name
{
member1;
member2;
………
………
};
where,
enum is the keyword which tells the compiler about enumerated type definition.
enum type_Name together represent the user defined data type.
member1,member2… are integer constants but represented using descriptive names.These are called
enumerator constants or enumerators.
The definition terminates with a semicolon.
Example
enum color
{
RED,
BLUE,
GREEN
};
enum color c1,c2;

enum days
{
SUNDAY,
MONDAY,
…….
SATURDAY
}d1;
Assigning values to Enumerated data types.
After an enumerated variable has been declared,we can store values in it. While the compile automatically assigns values to
enumerated types starting with 0,the next values are initilized with a value by adding 1 to previous value. For example, to
set up an enumerated type for the rain status, the following program could be used.
//Program by assining enum datatype
#include<conio.h>
enum status
{
low,medium,high
};
int main()
{
enum status rain;
rain=low;
if(rain==low)
printf(“\n rain status is low %d”,low);
return 0;
}
output
rain stauts is low 0
Self Referential Structures

Self Referential structures are those structures that have one or more pointers which point to the same type of
structure, as their member. In other words, structures pointing to the same type of structures are self-referential in
nature.
struct node {
int data1;
char data2;
struct node* link;
};

int main()
{
struct node ob;
return 0;
}
In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the structure ‘node’ is a self-referential
structure with ‘link’ as the referencing pointer.
An important point to consider is that the pointer should be initialized properly before accessing, as by default it
contains garbage value.
Types of Self Referential Structures
1.Self Referential Structure with Single Link #include <stdio.h>
struct node { Output
2.Self Referential Structure with Multiple Links
int data1; 30
Self Referential Structure with Single Link: These char data2; 40
struct node* link;
structures can have only one self-pointer as their
};
member. The following example will show us how to int main()
connect the objects of a self-referential structure with the {
single link and access the corresponding data members. struct node ob1; // Node1
The connection formed is shown in the following figure. // Initialization
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;
struct node ob2; // Node2
// Initialization
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;
// Linking ob1 and ob2
ob1.link = &ob2;
// Accessing data members of ob2 using ob1
printf("%d", ob1.link->data1);
printf("\n%d", ob1.link->data2);
return 0;
}
Self Referential Structure with Multiple Links: Self referential structures
with multiple links can have more than one self-pointers. Many complicated
data structures can be easily constructed using these structures. Such
structures can easily connect to more than one nodes at a time.

The following example shows one such structure with more than one links.
The connections made in the above example can be understood using the
following figure.
#include <stdio.h>
struct node { OUTPUT
int data; // Forward links
struct node* prev_link; ob1.next_link = &ob2;
struct node* next_link; ob2.next_link = &ob3; 10 20 30
}; 10 20 30
int main() // Backward links 10 20 30
{ ob2.prev_link = &ob1;
struct node ob1; // Node1 ob3.prev_link = &ob2;
// Initialization
ob1.prev_link = NULL; // Accessing data of ob1, ob2 and ob3 by ob1
ob1.next_link = NULL; printf("%d\t", ob1.data);
ob1.data = 10; printf("%d\t", ob1.next_link->data);
printf("%d\n", ob1.next_link->next_link->data);
struct node ob2; // Node2
// Initialization // Accessing data of ob1, ob2 and ob3 by ob2
ob2.prev_link = NULL; printf("%d\t", ob2.prev_link->data);
ob2.next_link = NULL; printf("%d\t", ob2.data);
ob2.data = 20; printf("%d\n", ob2.next_link->data);

struct node ob3; // Node3 // Accessing data of ob1, ob2 and ob3 by ob3
// Initialization printf("%d\t", ob3.prev_link->prev_link->data);
ob3.prev_link = NULL; printf("%d\t", ob3.prev_link->data);
ob3.next_link = NULL; printf("%d", ob3.data);
ob3.data = 30; return 0;
}
UNIT IV STRUCTURE AND POINTERS 09

Structure Introduction – Structure definition – Structure declaration –


Structure within a structure –Self Referential Structure. Pointers -
Definition – Initialization – Pointers arithmetic – Pointers and arrays -
Pointer to Function –Pointer and Structure- Simple programs.

Text Books
1. Balagurusamy. E, ―Programming in ANSI C, Tata McGraw Hill, 8thEdition,2019.
2. YashvantKanetkar, ―Let us C‖, BPB Publications, 16th Edition, 2017
3. Herbert Schildt,‖ C: The Complete Reference‖, McGraw Hill, FourthEdition,2014
Reference Books

1. Vikas B. Agarwal Jyoti P. Mirani, ―Computer Fundamentals , Nirali Prakashan Aug-2019,


2. Ashok N Kamthane, ―Computer Programming‖, Pearson education, Second Impression,2012.
3. VikasVerma, ―A Workbook on C ―, Cengage Learning, Second Edition,2012.
4. P.Visu, R.Srinivasan and S.Koteeswaran, ―Fundamentals of Computing and Programming‖, Fourth Edition, Sri
Krishna Publications, 2012.
5. PradipDev, ManasGhoush, ―Programming in C‖, Second Edition, Oxford University Press, 2011.
What is a Pointer
A pointer is defined as a derived data type that can store the address of other C variables or a memory location. We
can access and manipulate the data stored in that memory location using pointers.
As the pointers in C store the memory addresses, their size is independent of the type of data they are pointing to.
This size of pointers in C only depends on the system architecture.

Syntax of C Pointers
The syntax of pointers is similar to the variable declaration in C, but we use the ( * ) dereferencing operator in the
pointer declaration.

datatype * ptr;
where
ptr is the name of the pointer.
datatype is the type of data it is pointing to.
The above syntax is used to define a pointer to a variable. We can also define pointers to functions, structures,
etc.
How to Use Pointers?
The use of pointers in C can be divided into three steps:
Pointer Declaration
Pointer Initialization
Pointer Dereferencing
1. Pointer Declaration
In pointer declaration, we only declare the pointer but do not initialize it.
To declare a pointer, we use the ( * ) dereference operator before its
name.
Example
int *ptr;

The pointer declared here will point to some random memory address
as it is not initialized. Such pointers are called wild pointers.
2. Pointer Initialization
Pointer initialization is the process where we assign some initial value
to the pointer variable. We generally use the ( & ) addressof
operator to get the memory address of a variable and then store it in
the pointer variable.
Example
int var = 10;
int * ptr;
ptr = &var;

We can also declare and initialize the pointer in a single step. This
method is called pointer definition as the pointer is declared and
initialized at the same time.
Example
int *ptr = &var;

Note: It is recommended that the pointers should always be initialized


to some value before starting using it. Otherwise, it may lead to number
of errors.
3. Pointer Dereferencing
Dereferencing a pointer is the process of accessing the value stored in
the memory address specified in the pointer. We use the same ( * )
dereferencing operator that we used in the pointer declaration.
// C program to illustrate Pointers
#include <stdio.h>

void Point()
{
int var = 10;
// declare pointer variable
int *ptr;
// note that data type of ptr and var must be same
ptr = &var;
// assign the address of a variable to a pointer
printf("Value at ptr = %d \n", ptr);
printf("Value at var = %d \n", var);
printf("Value at *ptr = %d \n", *ptr);
}
// Driver program
int main()
{ Output
Point(); Value at ptr = 0x7fff1038675c
return 0; Value at var = 10
} Value at *ptr = 10
Pointer Arithmetic
Pointer Arithmetic is the set of valid arithmetic operations that can be performed on pointers. The pointer variables
store the memory address of another variable. It doesn’t store any value.
Hence, there are only a few operations that are allowed to perform on Pointers in C language. The C pointer
arithmetic operations are slightly different from the ones that we generally use for mathematical calculations. These
operations are:
Data Type Size Description Example

int 2 or 4 bytes Stores whole numbers, without decimals 1


1.Increment/Decrement of a Pointer
2.Addition of integer to a pointer float 4 bytes Stores fractional numbers, containing one or more 1.99
3.Subtraction of integer to a pointer decimals. Sufficient for storing 6-7 decimal digits
4.Subtracting two pointers of the same type
double 8 bytes Stores fractional numbers, containing one or more 1.99
5.Comparison of pointers decimals. Sufficient for storing 15 decimal digits

char 1 byte Stores a single character/letter/number, or ASCII 'A'


values

1. Increment/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.
For Example:
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.

You might also like