Structure, Pointer & File
Structure, Pointer & File
STRUCTURE:
A structure is a collection of different data fields. It is auser defined data type. A structure
definition has the following syntax:
struct structure-name
{
data-type-1 variable 1;
data-type-2 variable 2;
:
data-type-n variable n;
};
Here, “struct” is a keyword. “structure-name” is an identifier that represents the name of
the structure. The structure definition starts with an opening flower bracket and ends with
a closing flower bracket, followed by a semicolon. The data-type inside the structure
definition can be any data type. The variables declared inside a structure are called as
members of the structure.
EXAMPLE:
struct student
{
char name[20];
int age;
};
Here, “student” is name of structure & name, age are the members of the structure
student.
STRUCTURE VARIABLE DECLARATIONS:
A structure is also a data-type. So we can declare variable of its type. Such a variable
is called structure variable. The syntax to declare a structure variable is as follows:
struct structure-name structure-variable-name;
Here, structure-name is the name of the structure whose type of variable is to be
created.
For example, to declare a variable of type student, as defined in the above example,
struct student std1;
Now std1 becomes a structure variable of type student.
A structure-variable can also be declared when the structure is defined. It can be done as
follows:
structstruct-name
{ member-variable declarations;
} struct-variable1, struct-variable2,...struct-variableN;
Prepared by Khadar 9966648277
Example:
structstudent
{
char name[20];
int age;
} std1,std2;
Here we declared two structure variables std1 and std2.
ACCESSING MEMBERS:
The members of a structure are accessed using a special operator called member access
operator. It is denoted by a dot. The syntax to access a member of a structure is:
structure-variable.member-name;
For example, to assign a value to “age” member variables of “std1” structure variable, we
can do as follows:
std1.age=30;
structure initialization
Structure also we can initialize at the time of declaration like ordinary variable
and array. It syntax is :
struct structure-name var={list of constants};
example:
struct student
{
char name[15];
int id;
};
main()
{
struct student x={“Rahul”, 56};
--
}
Only constant we can initialize. Order of constant must be match with order of
members.
Prepared by Khadar 9966648277
BIT –FIELDS:
Bit-fields are extensions to primitive data-types where we can declare the exact number of
bits needed to store that variable. For example, an int variable takes 16-bits of memory
locations. Suppose we want a variable that takes values from 0 to 10 only. To store these
values only four-bits are enough. But if we declare that variable as an int, then it takes 16-
bits. So 12 bits are wasted. This can be saved using bit-fields. The following is the syntax:
data-type variable-name : no-of-bits;
Example:
int x:4;
x can be used to store a value which can fit in 4-bits.
UNION:
A union is a user defined type. It is a collection of different data-types. It is same as a
structure, but the memory allocated for a union variable is the memory required for the
largest data-type, whereas in a structure, the memory allocated for a structure variable is
the sum of memory required by all the members of that structure. So, at any point of time,
only any one member of the union can hold a value.
Syntax:
union union-name
{
data-type-1 variable-1;
data-type-2 variable-2;
:
data-type-n variable-n;
};
This is same as for structure, except that the keyword used here is “union”.
The total size of the above union will be 4-bytes only as it is the size of the largest data-
type. Now, if we assign;
x.j=20.5;
then the value in i will be lost because both the members use the same space in the
memory.
ARRAY OF STRUCTURES:
When we want to declare more number of same structure type variables then we declare
that structure type of array.
To store 10 students information in student structure, we declare structure student type of
array. Array of student structure is declared as follows:
struct student st[10];
syntax:
struct structure-name array-name[size];
struct structure_name
{
<data-type> member-1;
<data-type> member-2;
- - - - - - - - - - -
<data-type> member-n;
}inner_struct_var;
}outer_struct_var;
Example :
Struct student
{
intrno;
char name[50];
Prepared by Khadar 9966648277
struct subject
{
Char sub_name[30];
int marks;
}sub;
}result;
In above example, the structure student consists of subject which itself is a structure with
two members. Structure student is called as 'outer structure' while subject is called as
'inner structure.' The members which are inside the inner structure can be accessed as
follow :
result.sub.sub_name
result.sub.marks
ii)Syntax: Syntax:
data-type array-name[array-size]; struct structure-name
{
Members;
iii)Each member(data item) can accessed };
by using index Each member can accessed by dot or
member ship operator(.)
example :
struct address
{
char name[21];
char city[21];
char state[3];
};
struct addressa, *ptr;
ptr = &a;
Prepared by Khadar 9966648277
The pointer ptr is a pointer to a structure it takes two bytes of memory just like any other
pointer.
When pointers are used with structures, the members of structure can be accessed in two
ways. They are as follows;
(*ptr).member=value;
Or
Ptr->member=value;
self-referential structure
A self-referential structure contains a pointer member that points to a structure of the
same structure type. It is used to create data structures like linked lists, stacks,etc For
example.
struct node
{
int data;
struct node *next;
};
main()
{
struct node x , y,z;
x.data=40;
x.next=&y;
y.data=50;
y.next=&z;
z.data=30;
z.next=NULL;
printf(“\n value of y=%d”, x.next->data);
getch();
};
ENUMERATED DATA TYPE(ENUM) :- It is a user defined data types and is used to create set
of named constants. And enums are used as data type when we know all possible values of
variable at compile time,
Syntax:-
enume num-name{identifier1=value1,identifier2=value2,……};
Here “enum” is the keyword.
“enum-name” is the name of the enumerated data type being created and is optional.
Identifier1, identifier2,……. Can be any valid identifiers.
The identifiers can be assigned different values. If values are not specified the default
values are taken as 0,1,2,3,….
Prepared by Khadar 9966648277
Example :-
enum status{off,on}
Here off will be assigned 0 and on will be assigned 1.
Pointers
A pointer is a variable that holds the memory address of another variable.
5000 2000
2000 50
ptr var
Pointer declaration
Pointer also should be declared at the beginning of the function. The syntax of pointer
declaration is :
Pointer-type *pointer-name;
In the above declaration :
1. pointer-type : It specifies the type of pointer. It can be int, char, float etc. This type
specifies the type of variable whose address this pointer can store.
2. pointer-name : It can be any name specified by the user, but it should be valid.
3. ‘*’ signifies that ‘p’ is a pointer variable.
int *p;
In the above declaration, ‘int’ signifies the pointer type, p is the name of the pointer while
the asterisk ‘*’ signifies that ‘p’ is a pointer variable.
Advantages
Pointer operators
Example
int *p,n=100;
p=&n; /*stores the address of n*/
*p->100; /*the value of *p is 100*/
Pointer arithmetic
The arithmetic’s that can be performed on pointer variables are addition and subtraction.
We can perform addition or subtraction with only integers values. Pointer arithmetic is
different from normal arithmetic because it is performed relative to the base base-type of
the pointer. For example if an integer pointer is incremented by 1 then the address stored
in the pointer is incremented by 2 since the int take 2 bytes.
Prepared by Khadar 9966648277
int *p,n=0;/*assume n address is 5000*/
p=&n; /* p stores 5000 */
p++; /* now p stores 5002 */
inta[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int *p = a;
here first location address is assigned to p, because array name itself contains address of
array. After this declaration and initialization, ‘a’ and ‘p’ have the same value: same array
refers by both ‘a’ and ‘p’.
Example
Value of a[1] is 28 and p[1] value also 28 because both refers to same array. We can also
access the elements using address .
Example
But array name treated as constant pointer we can’t change the address which is store in
array name at run time.
malloc: The function malloc is used to allocate a certain amount of memory during the
execution of a program. If there is not enough memory available, the malloc function will
return a NULL. If the request is granted a block of memory is allocated (reserved) and
return The address of the reserved memory. tutorial
malloc allocates memory of specified size. and returns a pointer of type void. which
indicates that it is a pointer to unknown data type. So, it must be explicit cast to specific
pointer type. Memory allocate by malloc will continue to exit until the program
terminates or the memory is explicit deallocated.
Prepared by Khadar 9966648277
Example
A = (int*) malloc(N*sizeof(int));
Here A is a integer pointer and is N is a any integer. Hear N*sizeof(int) memory bytes
created.
calloc:
callac sued to allocate multiple blocks of memory dynamically during the execution (run-
time) of the program and then initializes it to zero. Its declaration syntax is :
A = (int*) malloc(N , sizeof(int));
There are 2 differences between these functions. First, malloc() takes a single argument
(the amount of memory to allocate in bytes), while calloc() needs 2 arguments (the number
of block to allocate in memory, and the size in bytes of a single block). Secondly, malloc()
does not initialize the memory allocated, while calloc() initializes the allocated memory to
ZERO.
Free:
The dynamically allocated memory exits until the program terminates or it is freed up
explicitly. The free function is used to free the memory. for example:
free(ptr);
whereptr is the pointer which point to address previously allocated by malloc or calloc;
realloc
If the previously allocated memory is insufficient or more than sufficient. Then, you can
change memory size previously allocated using realloc().
Ptr = realloc(ptr, newsize);
The "argc" variable gives the count of the number of command-line parameters
provided to the program. This count includes the name of the program itself.
The "argv" variable is refer the arguments values.
example:
/* test.c*/
#include <stdio.h>
Prepared by Khadar 9966648277
void main( int argc , char *argv[] )
{
int i;
for(i=1; i<argc; i++ )
{
scanf(“\n%s”,argv[i]);
}
}
Array of pointers
Just like array of integers or characters, We can also have array of
pointers. In This array each location stores the address of another
location. In this array each element refers to some element.
An array of pointers can be declared as :
<type> *<name>[size];
For example :
char *ptr[3];
example:
void main()
{
char *a[5];
int i;
printf(“enter the 5 names”);
for(i=0;i<5;i++)
scanf(“%s”,a[i]);
printf(“\n given names”);
for(i=0;i<5;i++)
Prepared by Khadar 9966648277
printf(“%s”,a[i]);
getch();
}
Files
A file is a storage area on the disk where a group of related data is stored,
and that data is referenced by a common name which is called as file-name.
dataof file is stored in secondary storage like hard disk, floppy disk, etc. each
file must have a unique name. The data stored in a file is stored permanently
and is non-volatile in nature. The common operations that can be performed
on a file are read, write, open, close, seek etc.
STREAMS:-
A stream is a sequence of bytes. It acts as a source from which the input data
can be obtained or as a destination to which output data can be sent.
i. The source stream that provides data to the program is called Input
stream. A program extracts the data from an input stream.
stream
PUT
DEVICE Program
ii. The destination stream that receives output from the program is called
the output stream. A program inserts the data into an output stream.
outputstreamInput
Output
DEVICEIN Program
iii. The data in the input stream can come from keyboard or any other
storage device.
iv. The data in the output stream can go to the screen or any other storage
device.
v. A stream acts as an interface between the program and I/O device.
File open
Before doing any operation on a disk, it has to be opened. The general
procedure to open a file is as follows:
Prepared by Khadar 9966648277
FILE *fp;
fp = fopen(“ file name “, “mode”);
the first line declare the variable “fp” as a pointer of type FILE. FILE is a data
type that is defined in I/O library. “file-name” is the name of the file that has
to opened. The “mode” specifies the purpose of opening the file. For
example “r” specifies that the file is being opened for reading. Similarly, “w”
specifies that the file is being is opened for writing.
Closing a file
A file must be closed when there are no operation that has to be performed
on it. This ensures that all outstanding information associated with the file is
flushed out from the buffer to the file. It also prevents any accidental misuse
of the file. If there is a limitation on number of files that can be opened
simultaneously, then closing the files that are not needed can be closed so
that the required files can be opened. Another instance where we have to
close a file is, when we want to reopen the same file in a different mode.
Syntax:
fclose(file-pointer);
ftell: By using ftell function we get current position of the file-pointer in the
file.
N= ftell(file-pointer);
This function is useful when we want to current position of the pointer. ftell
takes file pointer as a parameter and returns to integer value.
Value meaning
0 beginning of file
1 Current position
2 end of file
the offset may be positive, means move forward or negative, means move
backward. The following examples illustrate the operation of the fseek
function.
Prepared by Khadar 9966648277
Value meaning
fseek(ptr,0,0); Go to beginning
fseek(ptr,0,2); Go to end of the file
fseek(ptr,m,0);Move to m bytes from beginning
fseek(ptr,-m,2); go backward by m bytes from the end
Error handling:
The C programming language provides global variable “errno” and strerror()
functions for to handle the file errors. To make use of errno you need to
include errno.h.
errno: this is a global variable it give the error number. if error is come ,then
compiler will keep the value in this variable which is related to error.
strerror() : this function takes the “errno” as a parameter and return the
error message in the format of string .
#include <stdio.h>
#include <errno.h>
Prepared by Khadar 9966648277
#include <string.h>
void main () {
FILE *pf;
pf = fopen ("unexist.txt", "rb");
if (pf == NULL)
{
printf( "Value of errno: %d\n", errno);
printf( "Error opening file: %s\n", strerror( errno ));
}
-------
}