[go: up one dir, main page]

0% found this document useful (0 votes)
20 views70 pages

Structures, Pointers and Files in C

Uploaded by

pethu.tndalu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views70 pages

Structures, Pointers and Files in C

Uploaded by

pethu.tndalu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 70

Structures in C

A structure is a collection of related elements of


different data type, grouped under a single name.
The individual elements of a structure are known
as its members. The individual members of a
structure can be ordinary variables, pointers,
arrays or other structures.
Defining a structure
A structure may be defined as follows.
struct tag
{
type1 member1;
type2 member2;
……………
typem member m;
};
where
struct - keyword
tag - name of the structure
member1,……,member m - individual
members.
type1,………,typem - data types of
members.
Structures
Structure definition doesn’t tell the compiler to
reserve any space in the memory. Only when
structure variables are declared, space will be
reserved in the memory. Structure-type
variables can be declared as follows.
struct tag Variable1,Variable 2,
……..Variable n;
Example
struct employee
{
int empno; Structure definition
char name[10];
float salary;
}
Initialization
Structure variables can be initialized when
they are declared. The rules for structure
variables initialization are same as the rules of
array initialization. The values must be
enclosed in braces and separated by commas.
The general form is.

struct tag variable ={ Value 1,Value


2,..Value m};

Example

struct employee emp1={1,”siva”,


15000};
#include<stdio.h>
void main()
{
struct stud
{
int rollno;
char name[10];
int age;
};
struct stud
s1={111,”swapna”,20};
printf(“Address of rollno = %u \n”,
&s1.rollno);
printf(“Address of name= %u \n”,
s1.name);
printf(“Address of age = %u \n”,&s1.age);
printf(“Total size required = %d”,
sizeof(s1));
}
Assigning a Structure variable to
another
The values of structure variables can be
assigned to another structure variable of the
same type using the assignment operator. It may
be copying the individual elements one–by –one
or all at once. Also two structure variables of
same type can be compared with each other.
# include <string.h>
# include <stdio.h>
void main()
{
struct stud
{
int rollno;
char name[10];
int age;
};
struct stud s1={111,”swapna”,20};
struct stud s2,s3;
s2.rollno=s1.rollno; /* copying members one
by one */
strcpy(s2.name,s1.name);
s2.age = s1.age;
s3 = s1; /* copying all at
once */
printf (“%d%s
%d”,s1.rollno,s1.name,s1.age);
printf (“%d%s
%d”,s2.rollno,s2.name,s2.age);
printf (“%d%s
%d”,s3.rollno,s3.name,s3.age);
if (s1= =s2) /* Comparing
structure variables */
printf(“s1and s2 are same”);
else
printf(“s1and s2 are not
Nested Structures
When a structure includes another structure
variable as its member, it is called as a nested
structure. In such a situation, the declaration
of the embedded structure must appear before
the declaration of the outer structure.
void main()
{
struct address
{
char street[10],city[20];
int pin;
};
struct stud /* structure address declared
before this */
{
int rollno;
char name[10];
struct address addr;
};
struct stud s = {100,”priya”,”new
road”,”salem”,628091};
printf (“%d %s\n”, s.rollno,s.name);
printf (“%s %s %d\n”,
s.addr.street,s.addr.city,s.addr.pin);
}
Array of Structures
It is also possible to define an array of structure i.e., an
array in which each element is a structure.
Example
void main()
{
struct employee
{
int empno;
char name[10];
};
struct employee emp[5]; /* array of
structures */
int i;
printf (“enter 5 employee numbers and
names”);
for(i=0;i<4;i++) {
scanf (“%d %s”, emp[i].empno,
void main()
{
struct employee
{
int empno;
char name[10];
};
struct employee emp[5]; /* array of
structures */
int i;
printf (“enter 5 employee numbers and
names”);
for(i=0;i<=4;i++) {
scanf (“%d %s”, emp[i].empno,
emp[i].name);
printf(“the Employee number and names
Passing Structures to functions
A Structure can be passed to a function in 3
ways:
a. passing individual members to a function
b. passing the whole structure to a function
c. passing the address of a structure or a
member to a function
Passing individual members
Individual structure members can be passed as
arguments to a function. We are actually passing the
value of that member to the function. The arguments are
then treated independently as ordinary variables.

Example
#include <stdio.h>
void display(int,float);
void main() {
struct account
{
int accno;
float bal;
};
struct account a = {100,25000};
display(a.accno, a.bal); }
void display(int no, float balance) {
printf(“Account no :%d Balance : %f ”, no,
balance); }
#include <stdio.h>
void display(int,float);

void main()
{
struct account
{
int accno;
float bal;
};
struct account a = {100,25000};
display(a.accno, a.bal);
}
void display(int no, float balance)
{
printf(“Account no :%d Balance : %f ”, no,
balance); }
b. Passing the entire structure
When a structure is passed to a function, the
transfer is by value. i.e., the values will be copied
in a local structure and if any of the structure
variables are altered inside the function, the
changes will not be recognized in the calling
function. If we need the changes, the entire
structure has to be returned from the function.
Also we have to specify the type of the formal
parameters and return type.
#include <stdio.h>
void display (struct distance);
struct distance sum(struct distance, struct
distance);
void main( ) {
struct distance
{
int feet;
int inch;
}d1, d2, d3;
printf(“Enter 2 distances: feet & inch \n”);
scanf(“%d %d”,&d1.feet, d1.inch);
scanf(“%d %d”,&d2.feet, d2.inch);
printf(“Distance l is”)
display(d1); /* pass the structure
variable d1 */
printf(“Distance 2 is”);
display(d2); /* pass the structure
variable d2 */
d3 = sum(d1,d2);
printf(“Sum is \n”);
display(d3);
}
void display(struct distance d)
{
printf(“Feet : %d Inches %d \n”, d.feet, d.inch);
}
struct distance sum(struct distance dist1, struct
distance dist2)
{
struct distance dist3;
dist3.feet = dist1.feet + dist2.feet;
dist3.inch = dist1.inch + dist2.inch;
return dist3;
}
c. Passing the address of a structure
The address of a structure variable or member can
be passed as arguments using pointers. A structure
passed in this manner is said to be passed by
reference. Hence, if any of the structure members
are altered within the function, the changes will be
recognized in the calling function. Using the
pointer to the structure, the members of the
structure can be accessed with ->operator
#include <stdio.h>
struct distance
{
int feet;
int inch;
};
void increment(struct distance *);
void main( )
{
struct distance d = {10,1};
printf(“Before increment : %d %d”, d.feet, d.inch);
increment (&d);
printf(“After increment :%d %d”, d.feet, d.inch);
}
void increment(struct distance *dist)
{
(dist->feet)++;
(dist->inch)++;
}
Self-referential structures
If a member of a structure is a pointer to itself,
then it is said to be self-referential structures. Self
referential structures are very useful in
applications that involve linked data structures.
The general form is
struct tag
{
member 1;
member 2;
…………
struct tag *ptrname; /* pointer to itself */
};
where
void main()
{
struct stu
{
int rollno;
char name[20];
struct stu *ptr;
};
struct stu s1={111,”AAA”};
struct stu s2={222,”CCC”};
ptr=&s1;
s1.ptr=s2;
s2.ptr=NULL;
printf(“%d%S”,ptr->rollno, ptr->name);
printf(“%d%S”,s1.ptr->rollno, s1.ptr->name);
POINTERS in C
Pointers
A pointer is a variable that contains the address
of a data item such as a variable or an array
element. When it contains the address of an item,
it is said to point that item.
Significance of pointers
Basis of dynamic allocation of memory
very efficient method of accessing data.
Pointers are closely related with arrays and
hence they provide efficient techniques for
manipulating data in arrays
Used in functions as Pass-by-address
parameters.
Provide a convenient way to return multiple
data items from a function via function
Pointer Declaration
Like all other variables, pointer variables must be
declared before usage. The rules for naming the
pointer variables are same as identifiers. The
general form is
data-type *ptrvar;
where ptrvar is the name of the pointer variable
and data-type refers to the data type of the item
whose address is stored in the pointer ptrvar. The
asterisk (*) tells that the variable ptrvar is a
pointer variable.
Example int *p; /* pointer to an integer
variable*/
float *q; /* pointer to a float variable*/
Now p and q are declared as pointers which can
Size of pointer variable
The size of a pointer variable is 2 bytes irrespective
of the data type pointed by the pointer.
Example void main()
{
int *a;
float *b;
char *c;
printf("Size of the Integer pointer = %d\
n",sizeof(a));
printf("Size of the float pointer = %d\
n",sizeof(b));
printf("Size of the char pointer = %d\
n",sizeof(c));
Accessing pointer variables involve with two
operators:
a. Address operator (&)
b. Indirection or dereferencing operator (*)
a. Address operator (&)
This operator is used to obtain the address of a
variable. This operator may precede a variable
name or an array element but should not be used
before a constant or an expression. i.e. &5,
&(a+3) and &(4+i) are all invalid.
Example
/* Program for accessing variables through
pointers*/
#include <stdio.h>
void main()
{
int a = 3;
int *ptr; /* integer pointer */
ptr = &a; /* ptr points to a */
b = * ptr;
printf("a = %d address of a = %u
"a, &a);
printf("ptr = %u *ptr = %d b = %d ", ptr, *ptr,
b);
}
Example
#include <stdio.h>
void main()
{
int a = 3;
int *ptr; /* integer pointer */
ptr = &a; /* ptr points to a */
printf("Before change: *ptr = %d a = %d \n", *ptr,
a);
*ptr = 6; /* New value for a */
printf("After change: *ptr = %d a = %d \n", *ptr, a);
*ptr = *ptr + 1; /* Note the use of *ptr
on both sides*/
printf("After increment: *ptr = %d a = %d ", *ptr,
a);
(*ptr)++; /* Remember to use ( ) to evaluate
*ptr first*/
printf("After another increment: *ptr = %d a = %d
", *ptr, a);
Initialization of pointer variables
When we start our program, all the initialized
variables will have unknown garbage values in
them. It is true for pointers also. When the
program starts, uninitialized pointers will have
some unknown values in them.
Dereferencing uninitialized pointers always
leads to run time errors. To avoid this, we must
always assign a valid address to a pointer
variable.
Example int a;
int *ptr; /* integer pointer (declaration)
*/
ptr = &a; /* ptr now has a valid address
i.e.,address of a */
/* Using same pointer for multiple variables */
#include <stdio.h>
void main( ) {
int a, b, c;
int *p; /* integer pointer */
printf("Enter 3 numbers \n");
scanf("%d %d %d", &a, &b, &c);
p=&a; /* p points to a */
printf(" a = %d ", *p);
p=&b; /* p now points to b */
printf(" b = %d ", *p);
p=&c; /* p now points to c */
printf(" c = %d ", *p);
}
Operations on Pointers
Arithmetic and logical operations can be extended
to pointer variables also, but are very limited.
Arithmetic operations
Addition can be used when one operand is a pointer
and the other is an integer. Subtraction can be used
only when both operands are pointers or when first
operand is a pointer and the second operand is an
integer.
Suppose, for example, ptr is a pointer variable that
contains the address of a variable a.
i.e, int a, *ptr;
ptr = &a;
Relational operations
Two pointer variables of same type can be
compared for equality or inequality. Also pointer
variables can be compared with NULL constant.
Hence, the following expressions are all valid.
p1<p2 p1 = = p2 ptr = = NULL p1 >=
p2

The following operations are permitted on pointers.


Assigning the address of an ordinary variable to a
pointer For eg.,
int i = 1, *j;
j = &i;
Assigning the value of one pointer variable to another
pointer variable, provided both of them are of same
Assigning a NULL value to a pointer variable For eg.,
int *p = NULL;
Addition of a number to a pointer.
For eg., int i = 1, *j; j = &i; j = j + 5;
Subtraction of a number from a pointer. For eg.,
int i = 1, *j;
j = &i;
j = j - 2;
One pointer variable can be subtracted from another
provided both of them point to elements of the same
array.
Two pointer variables can be compared provided both
of them point to objects of same data type.
The following operations on pointers are not
permitted

Addition of 2 pointers
Multiplication of a number with a pointer
Dividing a pointer with a number
Assigning an arbitrary address by you to the
pointer variable.
Array of Pointers
Like an array of ints and an array of chars,
there is an array of pointers as well. Such an
array would simply be a collection of
addresses. Those addresses could point to
individual variables or another array as well.

dataType *variableName[size];

/* Examples */
int *a[5];
char *c[8];
int main()
{
int a,b,c;
int *ptr[3];
ptr[0]= &a;
ptr[1]= &b;
ptr[2]= &c;
a=100;
b=200;
c=300;
printf("value of a: %d, b: %d, c: d\
n",*ptr[0],*ptr[1],*ptr[2]);
*ptr[0] +=10;
*ptr[1] +=10;
*ptr[2] +=10;
printf("After adding 10\nvalue of a: %d, b: %d,
c: %d\n",*ptr[0],*ptr[1],*ptr[2]);

return 0;
}
Pointer to an Array

Array : Multiple values of same data type in a single variable

name
Pointer: It contains the address of an aother variable

Pointer to an Array : A pointer that points to the address of

the first element of the array


Syntax : int a[5]={10,20,30,40,50};

int *p;
p=a; // pointer p points to the starting address of an
array.
Traversing an array elements
*(p+i) is used to traverse the elements of
an array
where i represents the index of an
array.
Example:
*(p+0)- first element of an array
*(p+1)- second element of an array
*(p+2)- third element of an array
A Simple Program
#include <stdio.h>
int main()
{
int a[5]={10,20,30,40,50};
int *p , i;
p=a; OUTPUT
printf("The Elements of an array are \n"); The Elements of an array are
for (i=0 ; i<5;i++) 10
{ 20
printf("%d\n",*(p+i)); 30
40
}
50
return 0;
}
/* Program for pointer to an array */
int main () {
double balance[5] = {1000.0, 2.0, 3.4, 17.0,
50.0};
double *p;
float sum=0;
int i;
p = balance;
printf( "Array values using pointer\n");
for ( i = 0; i < 5; i++ ) {
sum=sum+*(p+i));
}
printf("sum=%f”,sum );
}
Adavntages of Pointer over an Array
Dynamic Memory Allocation : Using pointers, we can
allocate memory dynamically to an array.
The header file used for Dynamic memory allocation is
<stdlib.h>
Functions used for dynamic memory allocation are
malloc()
calloc()
free()
realloc()
malloc() function
“malloc” or “memory allocation” is used to
dynamically allocate a single large block of memory
with the specified size.
syntax:
ptr = (cast-type*) malloc(byte-size)
Example :
ptr = (int*)malloc(n*sizeof(int));
where n can be during the runtime of the
program
size of the ptr depends on the value of n
A Simple Program - malloc()
#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));
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
// deallocating the memory
free(ptr);
return 0;
}
calloc()
It dynamically allocates the specified number
of blocks of memory of the specified type
continuosly.
It initializes each block with a default value
‘0’.
It is called as continuous allocation method
syntax:
ptr = (cast-type*) calloc(n,byte-size);
Example :
 ptr=(int*)calloc(n,sizeof(int)); It allocates
the space for n elements continously.
A Simple Program - calloc() method
#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));
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
// deallocating the memory
free(ptr);
return 0;
}
realloc()
“realloc” or “re-allocation” method in C is used to
dynamically change the memory allocation of a
previously allocated memory. In other words, if the
memory previously allocated with the help of malloc
or calloc is insufficient, realloc can be used to
dynamically re-allocate memory.
syntax:
ptr = realloc(ptr, newSize);
Example
 ptr=realloc(ptr, n* sizeof(data-type));
where n is the new size
int main()
{
int n, i, *ptr,sum=0,sum1=0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) calloc(n, sizeof(int));
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
n=n+2;
ptr=(int*) realloc(ptr,n*sizeof(int));
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum1 += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
Array of Pointers or Pointer
Arrays
Array of the pointer variables.
Syntax
 int *array_name[size];

Example : int *a[3]; // It stores the array of


three pointer variables.
#include <stdio.h>
int main()
{
int a,b,c;
int *ptr[3];
/*assign the values to a,b,c*/
a=10;
b=20;
c=30;
/*assign the address of all integer variables to ptr*/
ptr[0]= &a;
ptr[1]= &b;
ptr[2]= &c;
/*print values using pointer variable*/
printf("value of a: %d, b: %d, c: %d\n",*ptr[0],*ptr[1],*ptr[2]);
return 0;
Structures and Pointers
#include<stdio.h>
#include<string.h>
struct student
{
char name[10];
int rollno;
};
int main()
{
struct student s = {"Akil", 123};
struct student *ptr; // pointer to a Structure variable
ptr =&s; //Assigns the starting address of the structure to the pointer
printf("Name: %s\n", ptr->name); // -> operator is used to access the members of a
structure using pointer
printf("Roll no %d\n", ptr->rollno);

// changing the name of a student


strcpy(ptr->name, "Sri");
printf("New name is: %s\n", ptr->name);
return 0;
}
Files in C Programming
Files
File acts like a container to store the data.
Need for Files
Storing in a file will preserve the data even if the program terminates.
Store large volume of persistent data
Easy Accessiblity
Types of Files
Text files
Text files are the normal .txt files. It can be created easily using any
simple text editors such as Notepad.
Easily readable, and provide the least security and takes bigger storage
space.
Binary files
Binary files are mostly the .bin files in a computer.Instead of storing
data in plain text, It stores the data in the binary form (0's and 1's).
They can hold a higher amount of data, are not readable easily, and
provides better security than text files.
File Operations

Creating a new file


Opening an existing file
Closing a file
Reading from and writing information to a
file
Creating a new File
Steps
 File pointer creation
File *ptr;
 Creating the file for opening and editing
ptr = fopen("fileopen","mode");
where fileopen- name of the file
mode- Mode of the file
File Modes
r opens a text file in read mode
w opens a text file in write mode
a opens a text file in append mode
r+ opens a text file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and write mode
rb opens a binary file in read mode
wb opens a binary file in write mode
ab opens a binary file in append mode
rb+ opens a binary file in read and write mode
wb+ opens a binary file in read and write mode
ab+ opens a binary file in read and write mode
File Operations
Opening a File
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen ("data.dat", "w");
}
Closing a File
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen ("data.dat", "r");
fclose (fp); }
Writing to a File
fputc(char, file_pointer): It writes a character to the file pointed
to by file_pointer.
fputs(str, file_pointer): It writes a string to the file pointed to by
file_pointer.
fprintf(file_pointer, str, variable_lists): It prints a string to the
file pointed to by file_pointer.
fputc()
#include <stdio.h>
int main() {
int i;
FILE * fptr;
char fn[20],str[]=”Welcome”;
fptr = fopen("test.dat", "w");
for (i = 0; str[i] != '\n'; i++) {
fputc(str[i], fptr); }
fclose(fptr);
return 0;
fputs()
#include <stdio.h>
int main() {
FILE * fp;
fp = fopen("test.dat", "w+");
fputs("Welcome to C Programming\n", fp);
fputs("Data Structures and Algorithms\n", fp);
fclose(fp); return (0); }
fprintf()
#include <stdio.h>
int main() {
FILE *fptr;
fptr = fopen("test.dat", "w");
fprintf(fptr, " C Programming\n");
fclose(fptr); return 0; }
Reading Data From a File

fgetc(file_pointer): It returns the next character from the file


pointed to by the file pointer.
fgets(buffer, n, file_pointer): It reads n-1 characters from the
file and stores the string in a buffer i
fscanf(file_pointer, conversion_specifiers, variable_adresses):
It is used to parse and analyze data.
#include <stdio.h>
int main() {
FILE * fp; char c;
printf("File Handling\n");
//open a file
fp = fopen("sample.txt", "w"); while ((c = getchar()) !
= EOF)
{ putc(c, fp); }
fclose(fp);
printf("Data Entered:\n");
//reading
fp = fopen("sample.txt", "r");
while ((c = getc(fp)) != EOF) {
printf("%c", c); } fclose(fp); return
0; }
Random Access File
fseek(), ftell() and rewind() functions are used to access the data in a file
randomly.
 ftell() function tells us about the current position in the file (in bytes).
 pos = ftell(fptr);

 Pos= 5 means 5 bytes of data are already read or written.

 rewind() function to return back to the starting point in the file.


rewind(fptr);
 fseek() function to move the file position to a desired location.
fseek(fptr, offset, position);
offset specifies the number of positions (in bytes) to move in the file
from the location specified by the position.
The position can take the following values.
0 - The beginning of the file
1 - The current position in the file
2 - End of the file
#include <stdio.h>
int main()
{
FILE * fp; /* File Pointer declaration */
int num,sno; /* Variable declarations */
char name[20];
float amount;
int i;
printf("\nEnter No. of records :");
scanf("%d",&num);
/* File opened in write then read mode (w+). */
if (( fp = fopen ("sample.txt", "w+" ) )== NULL ){
printf("\nERROR opening sample.txt file\n");
return(1);
}
else {
/* file is opened successfully*/
for ( i = 1 ; i <= num ; i++)
{
printf("Enter Name and Amount particulars : \n");
scanf("%s%f", name, &amount);
fprintf(fp,"\n%d %s %f", i,name, amount); /*write to file*/
}

rewind(fp); /*Adjust file pointer to beginning of the file */

printf("\n\t\t\tThe File Contents\n");


printf("SNo NAME AMOUNT \n");
while (! feof(fp) )
{
fscanf(fp, "%d%s%f",&sno,name,&amount);
printf("\n%d\t%s\t%f",sno,name,amount);
}
fclose(fp); /* close the file */

} /* end of if…else */ return 0; } /* end of main */

You might also like