Unit - 4
Pointers and Structure
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. ... int n = 10; int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.
Pointers in C language is a variable that stores/points the address of another variable. A Pointer in C is used to allocate memory dynamically i.e. at run time. The pointer variable might be belonging to any of the data type such as int, float, char, double, short etc.
Pointer Syntax : data_type *var_name; Example : int *p; char *p;
Where, * is used to denote that “p” is a pointer variable and not a normal variable.
Normal variable stores the value whereas a pointer variable stores the address of the variable.
The content of the C pointer always be a whole number i.e. address.
Always C pointer is initialized to null, i.e. int *p = null.
The value of null pointer is 0.
& symbol is used to get the address of the variable.
* symbol is used to get the value of the variable that the pointer is pointing to.
If a pointer in C is assigned to NULL, it means it is pointing to nothing.
Two pointers can be subtracted to know how many elements are available between these two pointers.
But, Pointer addition, multiplication, division are not allowed.
The size of any pointer is 2 byte (for a 16 bit compiler).
Example:
#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display q's value using ptr variable */
printf("%d", *ptr);
return 0;
Key takeaway :
One of the vital and heavily used features of ‘C’ is pointer. Most of the other programming languages also support pointers but only few of them use it freely. Support pointers but only few of them use it freely.
When we declare any variable in C language, there are three things associated with that variable.
1. Data type of variable : Data type defines the type of data that variable can hold. Data type tells the compiler about the amount of memory allocated to the variable.
2. Address of Variable : Address of variable represents the exact address of memory location which is allocated to variable.
3. Value of variable : It is the value of variable which is stored at the address of memory location allocated to variable.
Example : int n = 5;
In the above example ‘int’ is the data type which tells the compiler to allocate 2 bytes of memory to variable ‘n’.
Once the variable is declared the compiler allocated two bytes of memory to variable ‘n’. Suppose the address of that memory location is 1020. At the address of memory location 1020 the value 5 is stored.
Memory map for the above declaration is as follows.
use of &,/and ‘*’ operator
Consider the following program.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
printf(“Enter two numbers”);
scanf(“%d%d”, &a,&b);
c = a+b;
printf(“/n Addition is %d”, c);
printf(“/n Addition of variable is %d”, &c);
getch();
}
Above program is the program for addition of two numbers in ‘C’ language. In the seventh instruction of the above program we used operator ‘%’ and ‘&’ ‘%d’ is the access specifier which tells the compiler to take integer value as an input whereas. ‘&a’ tells the compiler to store the taken value at the address of variable ‘a’.
In the ninth instruction compiler will print me the value of ‘C’ so the output of the 9th instruction is as follows.
Addition is 5 [Note : considering a = 2 and b = 3]
In the tenth instruction compiler will print me the address of variable C.
So the output of length instruction is as follows. Address of variable C is 1020.
Now consider the following program.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
printf(“Enter two numbers”);
scanf(“%d%d”, &a,&b);
c = a+b;
printf(“/n Addition is %d”, c);
printf(“/n Addition of variable is %d”, &c);
printf(“/n value of variable c is %d”, *(&c));
getch();
}
Now, we all are clear about the output of instruction 9 and 10.
In the 11th instruction, operator *and & is used. ‘*’ operator tells compiler to pick up the value which is stored at the address of variable C. So the output of the 11th instruction is as follows. Value of variable C is 5 [considering a = 24 b = 3;]
Key takeaway :
Self -Referential structures are those structures that have one or more pointers which point to the same type of structure as their member.
The structures pointing to the same type of structures are self-referential in nature.
structnode {
intdata1;
chardata2;
structnode* link;
};
intmain()
{
structnode ob;
return0;
}
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.
Linked List is a collection of multiple nodes. Each node is connected to another node via link or pointer. Every node consists of two fields.
Data |
Address of next node |
Fig 1: Structure of a node
Data Field is used to store information and Address Field stores the memory address of the next node.
Fig 2: Structure of a Linked List
This Linked List consists of three nodes. First node is called the Head node. Assume that the first node is stored at memory location 1000.First node stores value 2 in data field. Second node starts at the memory address 2000 and hence 2000 is stored at the address field of the First node. Third node is located at memory location 3000 and hence 3000 is stored at address field of Second node. Same concept is used for all nodes in Linked List. Address field of the last node contains NULL as the last node does not point to any other node.
Types of Linked List:
We will discuss these types in more detail.
SINGLY LINKED LIST
Each node in the singly linked list points to the next node and it appears to move in one direction. Thus a singly linked list is unidirectional. Figure shows a schematic diagram of singly linked lists with 4 nodes.
Fig 3: singly linked list
DOUBLY LINKED LIST:
Singly or Circular Linked List can be traversed only in forward direction since nodes contain only one pointer field. Node in the doubly linked list contains one data field and two pointer fields.
Left link | Data | Right Link |
Fig 4: Structure of a node in DLL
Left Link points to predecessor node and right link points to successor node. Information is stored in the data field. Left link of First node and Right link of last node points to NULL. These two links enable bi-directional traversing, i.e. traversing the list in backward and forward direction. Hence called a bidirectional or doubly linked list.
CIRCULAR LINKED LIST:
A circular linked list is a linked list in which the last node points to the first node i.e next pointer of the last node points to the first node. Circular linked list does not contain NULL pointers.
Fig 5: circular linked list
Here A is the first node and C is the last node. C points to A and hence C stores address of A.
Key takeaway :
In the C programming language, the principle of dynamic memory allocation allows the programmer to assign memory at runtime. Four functions in the stdlib.h header file allow for dynamic memory allocation in the C language.
malloc() function
● The malloc() function allocates a single block of memory in response to a request.
● It does not initialize memory at runtime, so it starts with a garbage value.
● If memory is insufficient, it returns NULL.
● The following is the syntax for the malloc() function:
ptr=(cast-type*)malloc(byte-size)
Example :
#include<stdio.h>
#include<stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
Output
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30
calloc() function
● The calloc() function allocates several blocks of memory in response to a request.
● It starts by setting all bytes to zero.
● If memory is insufficient, it returns NULL.
● The calloc() function's syntax is as follows:
ptr=(cast-type*)calloc(number, byte-size)
Example :
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
Output
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30
realloc() function
● If malloc() or calloc() run out of memory, you can use the realloc() function to reclaim it. In a nutshell, it alters the memory size.
● Let's look at the realloc() function's syntax.
ptr=realloc(ptr, new-size)
free() function
● The memory used by the malloc() and calloc() functions must be freed by using the free() function. Otherwise, memory will be used before the program is terminated.
● Let's look at the free() function's syntax.
free(ptr)
Key takeaway :
● In the C programming language, the principle of dynamic memory allocation allows the programmer to assign memory at runtime.
● Four functions in the stdlib.h header file allow for dynamic memory allocation in the C language.
● The malloc() function allocates a single block of memory in response to a request.
● The calloc() function allocates several blocks of memory in response to a request.
● If malloc() or calloc() run out of memory, you can use the realloc() function to reclaim it.
● The memory used by the malloc() and calloc() functions must be freed by using the free() function.
Structure is a collection of different data types. An object of structure represents a single record in memory, if we want more than one record of structure type, we have to create an array of structure or object. As we know, an array is a collection of similar type, therefore an array can be of structure type.
Syntax for declaring structure array
struct struct-name
{
datatype var1;
datatype var2;
- - - - - - - - - -
- - - - - - - - - -
datatype varN;
};
struct struct-name obj [ size ];
Example for declaring structure array
#include<stdio.h>
struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
void main()
{
int i;
struct Employee Emp[ 3 ]; //Statement 1
for(i=0;i<3;i++)
{
printf("\nEnter details of %d Employee",i+1);
printf("\n\tEnter Employee Id : ");
scanf("%d",&Emp[i].Id);
printf("\n\tEnter Employee Name : ");
scanf("%s",&Emp[i].Name);
printf("\n\tEnter Employee Age : ");
scanf("%d",&Emp[i].Age);
printf("\n\tEnter Employee Salary : ");
scanf("%ld",&Emp[i].Salary);
}
printf("\nDetails of Employees");
for(i=0;i<3;i++)
printf("\n%d\t%s\t%d\t%ld",Emp[i].Id,Emp[i].Name,Emp[i].Age,Emp[i].Salary);
}
Output :
Enter details of 1 Employee
Enter Employee Id : 101
Enter Employee Name : Suresh
Enter Employee Age : 29
Enter Employee Salary : 45000
Enter details of 2 Employee
Enter Employee Id : 102
Enter Employee Name : Mukesh
Enter Employee Age : 31
Enter Employee Salary : 51000
Enter details of 3 Employee
Enter Employee Id : 103
Enter Employee Name : Ramesh
Enter Employee Age : 28
Enter Employee Salary : 47000
Details of Employees
101 Suresh 29 45000
102 Mukesh 31 51000
103 Ramesh 28 47000
In the above example, we are getting and displaying the data of 3 employee using
array of objects. Statement 1 is creating an array of Employee Emp to store the records
of 3 employees.
Array within Structure
As we know, structure is a collection of different data types. Like normal data type, It can
also store an array as well.
Syntax for array within structure
struct struct-name
{
datatype var1; // normal variable
datatype array [size]; // array variable
- - - - - - - - - -
- - - - - - - - - -
datatype varN;
};
struct struct-name obj;
Example for array within structure
struct Student
{
int Roll;
char Name[25];
int Marks[3]; //Statement 1 : array of marks
int Total;
float Avg;
};
void main()
{
int i;
struct Student S;
printf("\n\nEnter Student Roll : ");
scanf("%d",&S.Roll);
printf("\n\nEnter Student Name : ");
scanf("%s",&S.Name);
S.Total = 0;
for(i=0;i<3;i++)
{
printf("\n\nEnter Marks %d : ",i+1);
scanf("%d",&S.Marks[i]);
S.Total = S.Total + S.Marks[i];
}
S.Avg = S.Total / 3;
printf("\nRoll : %d",S.Roll);
printf("\nName : %s",S.Name);
printf("\nTotal : %d",S.Total);
printf("\nAverage : %f",S.Avg);
}
Output :
Enter Student Roll : 10
Enter Student Name : Kumar
Enter Marks 1 : 78
Enter Marks 2 : 89
Enter Marks 3 : 56
Roll : 10
Name : Kumar
Total : 223
Average : 74.00000
In the above example, we have created an array Marks[ ] inside structure representing
3 marks of a single student. Marks[ ] is now a member of structure student and to
access Marks[ ] we have used dot operator(.) along with object S.
Structure | Union |
A structure can be described with the struct keyword. | A union can be described using the union keyword. |
Every member of the structure has their own memory spot. | A memory location is shared by all data participants of a union. |
Changing the importance of one data member in the structure has no effect on the other data members. | When the value of one data member is changed, the value of the other data members in the union is also changed. |
It allows you to initialize several members at the same time. | It allows you to only initialize the first union member. |
The structure's total size is equal to the amount of each data member's size. | The largest data member determines the union's total size. |
It is primarily used to store different types of data. | It is primarily used to store one of the numerous data types available. |
It takes up space for every member mentioned in the inner parameters. | It takes up space for the member with the largest size in the inner parameters. |
It allows you to build a versatile collection. | A versatile array is not supported. |
Any member can be retrieved at any time. | In the union, you can only access one member at a time. |
The American Standard Code for Information Interchange (ASCII) is an acronym for American Standard Code for Information Interchange. A character collection of 128 7-bit characters that has been coded. The space character and the remove character are among the 32 control characters, 94 graphic characters, and the space character. The ASCII protocol consists of data encoded in ASCII values with just a few control codes. The printer interprets the control codes that are applied. ASCII communication is supported by all parallel, serial, and Ethernet mediums, and it is considered the industry standard.
Bits are tiny pieces of information that make up all data files. Each byte in an ASCII file corresponds to a particular character specified by the standard ASCII code. A text document produced without any formatting, such as font styles or paragraph indentations, is a common example of an ASCII file. A binary file containing ASCII codes is known as an ASCII file. There are 128 different ASCII codes, which means that an ASCII character can be represented with only 7 bits.
Binary files
Executables, sound files, image files, object files, and other types of binary files are all examples of binary files. The fact that each byte of a binary file can be one of 256-bit patterns is what makes them binary. Binary encoding, also known as BCP (Binary Communications Protocol), consists of values ranging from 0 to 255.
Binary files are made up of a long string of the characters "1" and "0" arranged in complex patterns. In contrast to ASCII, these characters can be used to construct any type of data, including text and images. In binary encoding, most language elements, such as integers, real numbers, and operator names, are expressed by fewer characters than in ASCII encoding.
Reading data from text files:
We can use the following methods to read text from text files:
read() - to read total data from file
read(n)- to read n char from a file
Read line()- to read only one line
Read line()- to read at lines into a list
Eg)
Code: Read all data
F = open(‘abc:txt’,’r’)
Data = f.read()
print(data)
f.close()
Output: Contents of ‘abc.txt’ will be printed
Eg)
code read lines:
F = open(‘abc.txt’,’r’)
Lines =f.read lines()
For line in lines:
Print (line,end = “ “)
F.close ()
Writing Data to text files:
We can write character data to text files by using the following 2 methods.
1)Write (str)
2)Writelines ( list of lines)
Eg: f=open(‘xyz.txt’,’w’)
f.write(‘SAE In’)
f.write(‘Kondhwa In’)
f.write(‘Pune’)
print(‘data are written successfully’)
f.close()
Note: In the given code, data present in the file will be overridden every time if w run the program. Instead of overriding if we want append operation then we should open the file as follows.
Key takeaway :
References :