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

Structure, Pointer & File

The document discusses various aspects of structures in C programming. It defines a structure as a collection of different data types that allows grouping of related data. It describes structure syntax, declaration, initialization, accessing members, nested structures, arrays of structures, pointers to structures, self-referential structures, and compares structures with arrays. It also discusses enumerated data types and pointers in C.

Uploaded by

rage
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views

Structure, Pointer & File

The document discusses various aspects of structures in C programming. It defines a structure as a collection of different data types that allows grouping of related data. It describes structure syntax, declaration, initialization, accessing members, nested structures, arrays of structures, pointers to structures, self-referential structures, and compares structures with arrays. It also discusses enumerated data types and pointers in C.

Uploaded by

rage
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Prepared by Khadar 9966648277

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”.

UNION VARIABLE DECLARATION:


A union variable can be declared same as a structure variable.
Syntax :
union union-name union-variable;
syntax:
union union-name
{
members of union;
}var1,var2,var3,…………….varn;
ACCESSING MEMBERS:
The members of a union are accessed using a dot operator. But at any point of time any
one member will be active.
Example:
union test
{
Prepared by Khadar 9966648277
int i;
floatj;
};
union test x; Declaring union variable
x.i=50; Accessing union member.

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];

STRUCTURE WITHIN STRUCTURE:

Structures can be used as structures within structures. It is also called as 'nesting of


structures'.
Syntax:
struct structure_name
{
<data-type> member-1;
<data-type> member-2;
- - - - - - - - - - -
<data-type> member-n;

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

COMPARE ARRAY AND STRUCTURE:


ARRAY STRUCTURE

i) Collection of same data elements Collection of different data type item

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(.)

Pointer to structures(structure pointer)


It is possible to create a pointer to almost any type in C, including user-defined types. It is
extremely common to create pointers to structures. The general form of pointer to
structure declaration is:

struct struct-name *ptr;

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

As shown in the above diagram:


 A normal variable ‘a’ has a memory address of 2000 and holds a value 50.
 A pointer variable has its own address 5000 but stores 2000, which is the address of the
variable ‘a’

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

1. dynamic memory allocation cannot be performed without using pointers.


2. using pointers is one way to have a function modify a variable passed to it.
3. Using pointer we can access the data quickly.
4. They can be used to return multiple values from a function via function arguments.
5. We save the memory by passing pointers (example passing arrays).

Pointer to Pointeror double pointer:


Prepared by Khadar 9966648277
Double pointer or pointer to pointer also a variable but it stores the address of single
pointer. Normally simple or single pointer stores the address of ordinary variable.
At the time of double pointer declaration we have to use an additional asterisk in front of
its name. For example, the following declaration declares a pointer to a pointer of type int.
int **p;
Double pointer memory representation

Address of Address of value


single pointer value

int a = 10, *x, **y;


x= &a;
y= &x;
here ‘a’ is a integer variable which stores the value 10, Now, we declared a integer
pointer ‘x’ and initialized it with the address of variable ‘a’.and double pointer ‘y’ and
initialized with the address of single pointer ‘x’;

Pointer operators

Operator Operator Name Purpose

* Value at Operator Gives Value stored at Particular address

& Address Operator Gives Address of Variable

1. ‘&’ operator is called as address or reference Operator, it gives the addres of


variable.
2. ‘*’ is called as ‘Value at address’ or “dereferencing”. this Operator gives ‘Value
stored at Particular address.

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 */

pointers and arrays


the name of an array holds the address of the first member of the array, it means array
name work as a pointer; we realize that we can declare a pointer of the same data type as
the array and initialize it with the array. Here is an example:

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

The value of *(a+1) is 28 and value of *(p+1) is also 28.

But array name treated as constant pointer we can’t change the address which is store in
array name at run time.

Dynamic memory allocation:


Memory allocation to variables can at compile time and other is run time. the allocation of
memory to variables at run time is called as dynamic memory allocation. Dynamic memory
allocation in C is based on three functions they are malloc, calloc and free.

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));

it allocate N blocks each of two(sizeof(int)) bytes.

Differences between malloc() and calloc()

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);

Command line arguments

main() function of a C program accepts arguments from command line, using


two optional parameters of "main()" named "argc (argument count)" and "argv
(argument vector)".

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]);
}
}

If this program is run from the command line as follows:


C:>test one two three

the output is:


one
two
three

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);

Disk or file input/output functions:


The functions that are used to read and write data from disk are called as
disk input/output functions. They are as follows.
fopen(): this function is used for opening a file. The specified file does not
exit, then a new file with the same name is created.
fclose(): this function is used for closing the file that is already open.
getc() or fgetc(): this function is used to read the character from the file.
putc() or fputc() : this function is used is used to write a character to a file.
fprintf(): this fuction is used to write data to a file.
fscanf(): this function is used to read data from a file.
getw() : this function is used to read an integer from a file.
putw(): this function is used to write an integer to a file
fseek(): this function is used to position the file pointer at the desired
location.
ftell(): this function returns the current position of filr pointer.
rewind(): this function resets the file pointer to the beginning of the file.

input and output operations on files:-


getc() or fgetc: this function is used to read a single character from a file
syntax :
ch = fgetc(file-pointer);
Prepared by Khadar 9966648277
thefgetc function read the character from the file which is refer by given file
pointer. The file-pointer is moved by one character for each read operation.
It returns EOF at the end of file.
fputc(): this function is used to write a single character to the file.
Syntax:
putc ( ch , file-pointer);
it writes the character from the first parameter “ch” to the file referenced by
file-pointer.

Random access to files


Random access is accessing a file randomly. It is useful when we want to
read some part of data, but not the whole file. This can be achieved with the
help of the functions fseek, ftell rewind, etc.

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.

rewind: by using rewind function we can takes file-pointer to starting


function. For example.
fewind(file-pointer);
fseek: fseek function is used to move the file-pointer position to a desired
location within the file it takes a following form.
fseek(ptr, offset, position);
ptris the file pointer, offset is an number or variable and position is an
integer number, the offset specifies the number of positions(bytes) to be
moved from the location specified by position. The position can take one of
the following three values.

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

text files and binary files


Depending upon the way file is opened for processing, a file is classified into
text file and binary file.
If a large amount of numerical data, images and videos etc. it to be stored,
text mode will be insufficient. In such case binary file is used.
Working of binary files is similar to text files with few differences in opening
modes, reading from file and writing to file.
fread and fwrite are the input and output functions for binary files instead of
fgetc and fputc
Opening modes of binary files:
Opening modes of binary files are rb, wb, rb+,wb+. The only difference
between opening modes of text and binary files is that, ‘b’ is appended to
indicate that, it is binary file.

Reading and writing of a binary file:


Functions fread() and fwrite() are used for reading from and writing to a file
on the disk respectively in case of binary files.
Function fwrite() takes four parameters, data address , size of data to be
written in disk, number of such type of data and pointer to the file where
you want to write.
fwrite(address_data,size_data,numbers_data,pointer_to_file);
Function fread() also take 4 arguments similar to fwrite() function as above.

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 ));
}
-------
}

You might also like