Pointers and Structures in C Programming
Pointers and Structures in C Programming
Structure
Syllabus
• Structures: Defining structures and Array of Structures,
• Pointers: Idea of pointers, Defining pointers, Use of Pointers
in self-referential structures, notion of linked list (no
implementation), bit-fields.
• File handling: concept of a file, text files and binary files,
Formatted I/O, file I/O operations(functions), example
programs
Structures
• Array is a collection of same type of elements but in many real life
applications we may need to group different types of logically related data.
• For example if we want to create a record of a person that contains name,
age and height of that person, then we can't use array because all the three
data element are of different types.
• To store these related fields of different data types we can use a structure,
which is capable of store heterogeneous data. Data of different types can be
grouped together under a single name using structure. The data elements of
a structure are referred to as members.
DEFINING A STRUCTURE
• Definition of a structure creates a template or format that describes the
characteristics of its members.
• All the variables that would be declared of this structure type, will take the
form of this template, general syntax of a structure definition is
struct tagname {
data type memberl;
datatype member2;
….………………
….……………….
datatype memberN;
};
• Here struct is a keyword, which tells the compiler that a structure is being
defined. member1, member2...............memberN are known as members of the
structure and are declared inside curly braces.
• These members can be of any data type like int, char, float, array, pointers or
another structure type. tagname is the name of the structure and it is used
further in the program to declare variables of this structure type.
Example
Let us take an example of defining a structure template.
struct student{
char name [20] ;
int rollno;
float marks;
};
Here student is the structure tag and there are three members of this
structure viz name, rollno and marks.
Structure template can be defined globally or locally i.e. it can be
placed before all functions in the program or it can be locally present in
a function.
If the template is global then it can be used by all functions while if it is
local then only the function containing it can use it.
DECLARING STRUCTURE VARIABLES
• By defining structure we have only created a format, the actual
use of structures will be when we declare variables based on
this format. We can declare structure variables in two ways
– With structure definition
– Using the structure tag
With Structure Definition
struct student{
char name [20] ;
int rollno;
float marks;
}stu1,stu2,stu3;
Here stu1, stu2 and stu3are variables of type struct student. When we declare a
variable while defining the structure template, the tagname is optional. So we can
also declare them as-
• structure{
char name [20] ;
int rollno;
float marks;
}stul,stu2,stu3;
If declare variables in this way, then we'll not be able to declare other variables of
this structure type anywhere else in the program nor can we send these structure
variables to functions. If a need arises to declare a variable of this type in the
program then we'll have to write the whole template again. So although the
tagname is optional it is always better to specify a tagname for the structure.
Using Structure Tag
We can also declare structure variables using structure tag. This can be written
as-
– struct student{
– char name [20] ;
– int rollno;
– float marks;
– };
• struct student stu1, stu2;
• struct student stu3;
• Here stu1, stu2 and stu3 are structure variables that are declared using the
structure tag student. Declaring a structure variable reserves space in
memory.
• Each structure variable declared to be of type struct student has three
members viz. name, rollno and marks.
• The compiler will reserve space for each variable sufficient to hold all the
members. For example each variable of type struct student will occupy 26
(20+2+4) bytes.
INITIALIZATION OF STRUCTURE
VARIABLES
The syntax of initializing structure variables is similar to that of arrays. All the
values are given in curly braces and the number, order and type of these values
should be same as in the structure template definition. The initializing values
can only be constant expressions.
struct student {
char name [20] ;
int rollno;
float marks;
}stu1={"Mary”,25,98};
struct student stu2={ "John”, 24, 67. 5};
Here value of members of stu1 will be "Mary" for name, 25 for rollno, 98 for
marks. The value of members of stu2will be "John"for name, 24 for rollno,
67.5 for marks.
We cannot initialize members while defining the structure.
Initialization
struct student {
char name [20] ;
int rollno;
float marks=99; / * Invalid * /
}stu;
Here the members rollno and marks of stul will be initialized to zero. This is
equivalent to the initialization
Output:
STORAGE OF STRUCTURES IN
MEMORY
The members of structures are stored in consecutive memory locations.
Program 3: Program to show that members of structure are stored in consecutive
memory locations.
#include<stdio.h>
main()
{
struct student {
char name[5];
int rollno;
float marks;
}stu;
printf("Address of name = %u \n",[Link]);
printf("Address of rollno = %u\n",&[Link]);
printf("Address of marks = %u\n" ,&[Link]);
}
Output:
ARRAY OF STRUCTURES
• We know that array is a collection of elements of same
datatype. We can declare array of structures where each
element of array is of structure type. Array of structures can
be declared as
Output :
Pointers
POINTER CONCEPT
• C is a very powerful language and the real power of C lies in
pointers.
• The concept of pointers is interesting as well as challenging.
• It is very simple to use pointers provided the basics are understood
thoroughly.
• So it is necessary to visualize every aspect of pointers instead of
just having a superficial knowledge about their syntax and usage.
• The use of pointers makes the code more efficient and compact.
#include<stdio.h>
void main( )
{
int age=30;
float sal=1500.50;
printf ("Value of age=%d,Address of age= %u\n",age,&age);
printf ("Value of sal=%f, Address of sal= %u\n",sal,&sal);
}
Output:
POINTER VARIABLE
• A pointer is a variable that stores memory address.
• Like all other variables it also has a name, has to be declared
and occupies some space in memory.
• It is called pointer because it points to a particular location in
memory by storing the address of that location.
Declaration of Pointer Variables
• Like other variables, pointer variables should also be declared before being used.
The general syntax of declaration is
• data_ type *pname;
Here,
• pname → is the name of pointer variable, which should be a valid C identifier.
• asterisk * → preceding this name informs the compiler that the variable is declared
as a pointer.
Here data type is known as the base type of pointer. Let us take some pointer
declarations
• int *iptr;
• float *fptr;
• char *cptr;
• Here iptr is a pointer that should point to variables of type int, similarly fptr and
cptr should point to variables of float and char type respectively.
• Pointers are also variables so compiler will reserve space for them and they will
also have some address.
• All pointers irrespective of their base type will occupy same space in memory since
all of them contain addresses only.
Initialization of pointer variables
• When we declare a pointer variable it contains garbage value i.e, it may be pointing
anywhere in the memory.
• So we should always assign an address before using it in the program. The use of
an unassigned pointer may give unpredictable results and even cause the program to
crash.
• Pointers may be assigned the address of a variable using assignment statement.
For example:
• int *ptr, age = 30;
• float *fptr, sal = 1500.50;
• iptr = &age;
• ptr = &sal;
• Now iptr contains the address of variable age i.e. it points to variable age, similarly
fptr points to variable sal. Since iptr is declared as a pointer of type, int, we should
assign address of only integer variables to it.
• If we assign address of some other data type then compiler won't show any
error ,but the output will be incorrect.
Example
Initialization of pointer variables
• We can also initialize the pointer at the time of declaration.
But in this case the variable should be declared before the
pointer. For example
• int age = 30, *iptr = &age;
• float sal = 1500.50, *fptr = &sal;
• ptr = NULL;
Dereferencing Pointer Variables
• Till now we have done a lot of programming and in all our
programs we have used the name of a variable for accessing it.
• We can also access a variable indirectly using pointers.
• For this we will use the indirection operator(*).
• By placing the indirection operator before a pointer variable,
we can access the variable whose address is stored in the
pointer. Let us take an example
• int a = 87
• float b= 4.5;
• int *p1 = &a;
• float *p2 = &b;
Continued….
• The indirection operator can be read as 'value at the
address'.
• For example *pl can be read as value at the address p1.
• This indirection operator (*) is different from the asterisk that
was used while declaring the pointer variable.
Continued….
• In our program, if we place ‘*’ before p1 then we can access the variable
whose address is stored in p1.
• Since p1 contains the address of variable a, we can access the variable a by
writing *p1.
• Similarly we can access variable b by writing *p2. So we can use *pl and
*p2 in place of variable names a and b anywhere in program.
•
Program 2
//Program to dereference pointer variables.
#include<stdio.h>
void main()
{
int a=87;
float b=4.5;
int *p1=&a;
float *p2=&b;
printf ("Value of pl =Address of a=%u\n",p1);
printf ("Value of p2 =Address of b=%u\n",p2);
printf ("Address of pl %u \n" ,&p1) ;
printf ("Address of p2 %u \n", &p2) ;
printf( "Value of a=%d %d %d\n",a,*p1,*(&a)) ;
printf ("Value of b=%f %f %f\n",b,*p2,*(&b)) ;
}
Output:
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.
Continued…
• In other words, structures pointing to the same type of
structures are self-referential in nature.
• Example:
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob;
return 0;
}
Continued…
• 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
Output:30 40
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.
Continued….
Bit Fields
• In C, we can specify size (in bits) of structure and union
members.
• The idea is to use memory efficiently when we know that the
value of a field or group of fields will never exceed a limit or
is within a small range.
• For example, consider the following declaration of date
without the use of bit fields.
Program 4
#include <stdio.h>
struct date
{
unsigned int d;
unsigned int m;
unsigned int y;
};
int main()
{
printf("Size of date is %lu bytes\n",sizeof(struct date));
struct date dt = { 31, 12, 2014 };
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
}}
Output:
Program 2: r mode
#include<stdio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("[Link]","r");
while(fscanf(fp,"%c",&ch)!=EOF)
printf("%c",ch) ;
fclose(fp);
return(0);
}
output:
Program 3: a mode
#include <stdio.h>
int main ()
{
FILE * fp;
fp = fopen ("[Link]", "a");
fprintf(fp, "%s ", "We are going in 2022”);
fclose(fp);
return(0);
}
Output :
Program 4: r+ mode
#include <stdio.h>
int main() {
FILE *fp;
char ch;
fp = fopen("[Link]","r+");
while(fscanf(fp,"%c",&ch)!=EOF)
printf("%c",ch) ;
fprintf(fp, "%s", "We are indians");
fclose(fp);
return(0);
}
Output:
Program 5: a+ mode
#include <stdio.h>
int main() {
FILE *fp;
char ch;
fp = fopen("[Link]","a+");
while(fscanf(fp,"%c",&ch)!=EOF)
printf("%c",ch) ;
fprintf(fp, "%s %s %s %d", "We", "are", "in", 2019);
fclose(fp);
return(0);
}
Output:
Program 6: w+ mode
#include <stdio.h>
int main() {
FILE *fp;
char ch;
fp = fopen("[Link]","w+");
fprintf(fp, "%s", "We are in 2019");
fseek(fp,0L,0);
while(fscanf(fp,"%c",&ch)!=EOF)
printf("%c",ch) ;
fclose(fp);
return(0);
}
Output :
Closing a File
• The file that was opened using fopen () function must be closed when no more operations are
to be performed on it. After closing the file, connection between file and program is broken.
Declaration:
• int fclose(FILE *fptr);
• Although all the files are closed automatically when the program terminates normally, but
sometimes it may be necessary to close the file by fclose( ).
• If more than one files are opened, then we can close all the files by calling fclose( ) for each
• fclose(fptrl) ;
• fclose(fptr2) ;
I/O OPERATIONS/FUNCTIONS
fputc ( )
• Declaration: int fputc( int c, FILE *fptr);
• The function writes a character to the specified file at the
current file position and then increments the file position
pointer.
• On success it returns an integer representing the character
written, and on error it returns EOF.
Program 7
//Program to understand the use of fputc() function.
#include<stdio.h>
int main()
{
FILE *fptr;
int ch;
fptr=fopen("[Link]","w");
printf("enter text:\n");
while ((ch=getchar())!=EOF)
fputc(ch,fptr);
fclose(fptr);
}
Output:
fgetc()
#include<stdio.h>
main()
{
FILE *p;
int ch;
p=fopen("[Link]","r");
while((ch=fgetc(p))!=EOF)
printf("%c",ch);
fclose(p);
}
Output:
Integer I/O
• putw ( )
Declaration: int putw(int value, FILE *fp)
• putw function is used to write an integer into a
file.
• In a C program, we can write integer value in a
file as below.
putw(i, fp);
• where
i – integer value
fp – file pointer
Program 9
//Program to understand the use of putw() function.
#include<stdio.h>
main()
{
FILE *fptr;
int value;
fptr=fopen("[Link]","w");
value=65;
putw(value,fptr);
fclose(fptr);
}
Output:
getw()
• fputs()
• Declaration: int fputs(const char *str, FILE *fptr);
• This function writes the null terminated string pointed to by str
to a file.
• The null character that marks the end of string is not written to
the file.
• On success it returns the last character written and on error it
returns EOF.
Program 11
Program to understand the use of fputs() function.
#include<stdio.h>
main()
{
FILE *fptr;
char str[80]= "Tom and Jerry are Good Friends..";
fptr=fopen("[Link]","w");
fputs(str,fptr);
fclose(fptr);
}
Output :
fgets( )
Output:
Formatted I/O
• fprintf ( )
• fprintf ( FILE *fptr, const char *format [, argument, ... ] );
• This function is same as the printf ( ) function but it writes formatted data
into the file instead of standard output (screen). This function has same
parameters as in printf( ) but it has one additional parameter which is a
pointer of FILE type, that points to the file to which the output is to be
written. It returns the number of characters· output to the file on success,
and EOF on error.
Program 13
//Program to understand the use of fprintf() function.
#include<stdio.h>
main()
{
FILE *fp;
char name[10];
int age;
fp=fopen("[Link]","w") ;
printf("Enter your name and age");
scanf("%s%d",name,&age) ;
fprintf(fp,"My name is %s and age is %d",name,age);
fclose(fp) ;
}
Output:
Program
Program to understand the use of fprintf() function.
14
#include<stdio.h>
struct student{
char name[20];
float marks;
}stu;
main()
{
FILE *fp;
int i,n;
fp=fopen("[Link]","w");
printf("Enter number of records ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("Enter name and marks");
scanf("%s%f",[Link],&[Link]);
fprintf(fp,"%s %f",[Link],[Link]);
}}
Output:
fscanf ( )
#include<stdio.h>
struct student{
char name[20];
float marks;
}stu;
main()
{
FILE *fopen(),*fp;
fp=fopen("[Link]","r");
printf ("NAME\tMARKS\n");
while(fscanf(fp,"%s%f",[Link],&[Link])!=EOF)
printf("%s\t%f\n",[Link],[Link]) ;
fclose(fp) ;
}
Output:
Record I/O
fwrite( ): The fwrite() function is used to write records (sequence of
bytes) to the file. A record may be an array or a structure.
Declaration: size_t fwrite( const void *ptr, size_t size, size_t n, FILE *fptr );
int main () {
FILE *fp;
fp = fopen("[Link]","w+");
fputs("This is [Link]", fp);
return(0);
}
Output:
ftell( )
• This function is used to move the file position pointer to the beginning of
the file. Here fptr is a pointer of FILE type. The function rewind( ) is useful
when we open a file for update.
Program 20
#include<stdio.h>
#include<stdlib.h>
main()
{
FILE *fp;
fp=fopen(“[Link]","r");
printf("position pointer->%ld\n",ftell(fp));
fseek(fp,0,2);
printf("position pointer->%ld\n",ftell(fp));
rewind(fp);
printf("Position pointer ->%ld\n",ftell(fp));
fclose(fp);
}
Output:
Merge contents of two files into a
third file
• Let the given two files be [Link] and [Link].
• The following are steps to merge.
1) Open [Link] and [Link] in read mode.
2) Open [Link] in write mode.
3) Run a loop to one by one copy characters of [Link] to [Link].
4) Run a loop to one by one copy characters of [Link] to [Link].
5) Close all files.
Program 21
//Program that concatenate two files which appends the content of one file to the end of another file and write the result in third file.
#include <stdio.h>
int main()
{
// Open two files to be merged
FILE *fp1 = fopen("[Link]", "r");
FILE *fp2 = fopen("[Link]", "r");
fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}
Output :