SlideShare a Scribd company logo
1 of 37
Download to read offline
1
UNIT - V
POINTERS, STRUCTURES & UNIONS, DATA FILES
Pointers: Concept of a Pointer, Initialization of pointer variables, pointers as function
arguments, address arithmetic, pointers to pointers, Pointers and arrays, Array of Pointers,
Dynamic memory management functions, parameter passing by address.
Structures and Unions: Structures declaration, Initialization of structures, accessing
structures,unions
Data Files: Declaring, Opening, and Closing File Streams, Reading from and Writing to
Text Files.
S.NO TOPIC PAGE NUMBER
1. Pointer declaration &
Initialization
2
2. Pointer as function argument 4
3. NULL pointer 3
4. Generic or void pointer 4
5. Address arithmetic 6
6. Pointer to pointer(or)double
pointer
9
7. Pointer and arrays 10
8. Array of pointer 13
9. Dynamic memory allocation 16
10. Parameter passing techniques 19
11. Structure declaration&
initialization
20
12. Accessing of structure
elements
21
13. Array of structures 22
14. Union 25
15. Declaration of file 28
16. Opening a file 29
17. Closing a file 31
18. Reading from and writing
into text file
31
2
ADDRESS IN C:
If you have a variable ‘var’ in your program, ‘&var’ will give you its address in the memory,
where & is commonly called the reference operator.
This notation is seen in the scanf function. It is used in the function to store the user inputted
value in the address of var.
scanf("%d", &var);
Program:
#include <stdio.h>
int main()
{
int var = 5;
printf("Value: %dn", var);
printf("Address: %u", &var); //Notice, the ampersand(&) before var.
return 0;
}
Output:
Value: 5
Address: 2686778
POINTERS:
A pointer is a variable whose value is the address of another variable, i.e., direct address of the
memory location. Like any variable or constant, you must declare a pointer before using it to
store any variable address.
Declaration:
data_type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name
of the pointer variable.
Examples:
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
Initialization of pointer variable:
The initialization of a pointer variable is similar to other variable initialization, but in the
pointer variable we assign the address instead of value.
int *ptr, var;
3
ptr = &var;
In the above example we have a pointer variable (*ptr) and a simple integer variable (var). We
have to assign the pointer variable to the address of ‘var’. It means that the pointer variable
‘*ptr’ now has the address of the variable ‘var’.
REFERENCE OPERATOR (&) AND DEREFERENCE OPERATOR (*):
&is called reference operator which gives the address of a variable.Likewise, there is another
operator that gets you the value from the address, it is called a dereference operator
(*).Note: The * sign when declaring a pointer is not a dereference operator.
Program:
#include <stdio.h>
int main(){
int *pc;
int c;
c=22;
printf("Address of c:%un",&c);
printf("Value of c:%dn",c);
pc=&c;
printf("Address of pointer pc:%un",pc);
printf("Content of pointer pc:%dn",*pc);
c=11;
printf("Address of pointer pc:%un",pc);
printf("Content of pointer pc:%dn",*pc);
*pc=2;
printf("Address of c:%un",&c);
printf("Value of c:%dn",c);
return 0;
}
Output:
Address of c: 2686784
Value of c: 22
Address of pointer pc: 2686784
Content of pointer pc: 22
Address of pointer pc: 2686784
Content of pointer pc: 11
Address of c: 2686784
Value of c: 2
4
NULL POINTERS: It is always a good practice to assign a NULL value to a pointer variable
in case you do not have an exact address to be assigned. This is done at the time of variable
declaration. A pointer that is assigned NULL is called a nullpointer.
#include <stdio.h>
int main () {
int *ptr = NULL;
printf("The value of ptr is : %xn", ptr );
return 0;
}
Output:
The value of ptr is 0
GENERIC POINTERS: It is a pointer variable that has void as its data type. It can be used
to point to variables of any type.
void *ptr;
In C, since we cannot have a variable of type void, the void pointer will therefore not point to
any data and thus cannot be dereferenced. We need to typecast a void pointer to another kind
of pointer before using it. It is often used when we want a pointer to point to data of different
types at different time.
#include <stdio.h>
int main () {
int x=10;
void *ptr;
ptr = &x;
printf(“generic pointer points to the integer value %d”, *(int*)ptr);
return 0;
}
Output:
Generic pointer points to the integer value 10
POINTERS AS FUNCTION ARGUMENTS:
C programming allows passing a pointer to a function. To do so, simply declare the function
parameter as a pointer type and send the addresses of the variables in the function call.
Program: to swap two numbers using pointers and function.
#include <stdio.h>
void swap(int *n1, int *n2);
int main()
{
5
int num1 = 5, num2 = 10;
swap( &num1, &num2); // address of num1 and num2 is passed to the swap function
printf("Number1 = %dn", num1);
printf("Number2 = %d", num2);
return 0;
}
void swap(int * n1, int * n2)
{
// pointer n1 and n2 points to the address of num1 and num2 respectively
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
Output:
Number1 = 10
Number2 = 5
• The address of memory location num1 and num2 are passed to the function swap and
the pointers *n1 and *n2 accept those values.
• So, now the pointer n1 and n2 points to the address of num1 and num2 respectively.
• When, the value of pointers are changed, the value in the pointed memory location also
changes correspondingly.
• Hence, changes made to *n1 and *n2 are reflected in num1 and num2 in the main
function.
• This technique is known as Call by Reference in C programming.
DANGLING POINTERS:
• Dangling pointers arise when an object is deleted or de-allocated, without modifying
the value of the pointer, so that the pointer still points to the memory location of the de-
allocated memory.
• In short pointer pointing to non-existing memory location is called dangling pointer.
Examples:
Way 1 : Using free or de-allocating memory
#include<stdlib.h>
{
char *ptr = malloc(Constant_Value);
.......
.......
6
.......
free (ptr); /* ptr now becomes a dangling pointer */
}
We have declared the character pointer in the first step. After execution of some statements we
have de-allocated memory which is allocated previously for the pointer.
As soon as memory is de-allocated for pointer, pointer becomes dangling pointer
How to Ensure that Pointer is no Longer Dangling ?
#include<stdlib.h>
{
char *ptr = malloc(Constant_Value);
.......
.......
.......
free (ptr); /* ptr now becomes a dangling pointer */
ptr = NULL /* ptr is no more dangling pointer */
}
After de-allocating memory, initialize pointer to NULL so that pointer will be no longer
dangling. Assigning NULL value means pointer is not pointing to any memory location
Way 2 :Out of Scope
#include<stdlib.h>
void main()
{
char *ptr;
.....
.....
{
char ch;
ptr = &ch;
}
.....
}
Character pointer is declared in the first step. Pointer variable ‘ptr’ is pointing to character
variable ‘ch’ declared in the inner block . As character variable is non-visible in outer block,
then pointer is still pointing to same invalid memory location in outer block , then pointer
becomes “dangling”.
7
POINTER ARITHMETIC:
A pointer in C is an address, which is a numeric value. Therefore, you can perform arithmetic
operations on a pointer just as you can on a numeric value. There are the arithmetic operators
that can be used on pointers: ++, --. To understand pointer arithmetic, let us consider
that ptr is an integer pointer which points to the address 1000. Let us perform the following
arithmetic operation on the pointer –
ptr++
After the above operation, the ptr will point to the location 1002 because each time ptr is
incremented, it will point to the next integer location which is 2 bytes next to the current
location. If ptr points to a character whose address is 1000, then the above operation will point
to the location 1001 because the next character will be available at 1001.
Incrementing a Pointer:
Program: to increment the variable pointer to access each succeeding element of the array
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have array address in pointer */
ptr = var;
for ( i = 0; i < MAX; i++) {
printf("Address of var[%d] = %xn", i, ptr );
printf("Value of var[%d] = %dn", i, *ptr );
ptr++; /* move to the next location */
}
return 0;
}
Output:
Address of var[0] = bf882b30
Value of var[0] = 10
Address of var[1] = bf882b32
Value of var[1] = 100
Address of var[2] = bf882b34
Value of var[2] = 200
Decrementing a Pointer:
Program:
#include <stdio.h>
const int MAX = 3;
8
int main () {
int var[] = {10, 100, 200};
int i, *ptr;
ptr = &var[MAX-1]; /* let us have array address in pointer */
for ( i = MAX; i > 0; i--) {
printf("Address of var[%d] = %xn", i-1, ptr );
printf("Value of var[%d] = %dn", i-1, *ptr );
ptr--; /* move to the previous location */
}
return 0;
}
Output:
Address of var[2] = bfedbcd8
Value of var[2] = 200
Address of var[1] = bfedbcd6
Value of var[1] = 100
Address of var[0] = bfedbcd4
Value of var[0] = 10
CHARACTER POINTERS:
Consider the following example:
char arr[] = "Hello World"; // array version
char ptr* = "Hello World"; // pointer version
Similarity between them:
The type of variable is a pointer to char or (char*), so you can pass either of them to a function
whose formal argument accepts an array of characters or a character pointer.
Difference between them:
arr is an array of 12 characters. When compiler sees the statement:
char arr[] = "Hello World";
It allocates 12 consecutive bytes of memory and associates the address of the first allocated
byte with arr.
On the other hand when the compiler sees the statement.
char ptr* = "Hello World";
It allocates 12 consecutive bytes for string literal "Hello World" and 2 extra bytes for pointer
variable ptr. And assigns the address of the string literal to ptr. So, in this case, a total
of 14 bytes are allocated.
9
After the above assignment, ptr points to the address of "Hello World" which is stored
somewhere in the memory.
How do we assign a different string to arr ?
We can assign a new string to arr by using gets(), scanf(), strcpy() or by assigning characters
one by one.
Example:
gets(arr);
scanf("%s", arr);
strcpy(arr, "new string");
arr[0] = 'R';
arr[1] = 'e';
arr[2] = 'd';
arr[3] = ' ';
arr[4] = 'D';
arr[5] = 'r';
arr[6] = 'a';
arr[7] = 'g';
arr[8] = 'o';
arr[9] = 'n';
Modifying a string literal causes undefined behavior, so the following operations are invalid.
char *ptr = "Hello";
ptr[0] = 'Y'; or *ptr = 'Y';
gets(name);
scanf("%s", ptr);
strcpy(ptr, "source");
strcat(ptr, "second string");
Using an uninitialized pointer may also lead to undefined undefined behavior.
char *ptr;
Here ptr is uninitialized an contains garbage value. So the following operations are invalid.
ptr[0] = 'H';
gets(ptr);
scanf("%s", ptr);
strcpy(ptr, "source");
strcat(ptr, "second string");
We can only use ptr only if it points to a valid memory location.
char str[10];
char *p = str;
Now all the operations mentioned above are valid.
10
POINTER TO POINTERS:
A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a
pointer contains the address of a variable. When we define a pointer to a pointer, the first
pointer contains the address of the second pointer, which points to the location that contains
the actual value as shown below.
Declaration:
int **var; //declares a pointer to pointer of type int
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value
requires that the asterisk operator be applied twice, as is shown below in the example:
Program:
#include <stdio.h>
int main () {
int var;
int *ptr;
int **pptr;
var = 3000;
ptr = &var; /* take the address of var */
pptr = &ptr; /* take the address of ptr using address of operator & */
printf("Value of var = %dn", var ); /* take the value using pptr */
printf("Value available at *ptr = %dn", *ptr );
printf("Value available at **pptr = %dn", **pptr);
return 0;
}
Output:
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000
POINTERS AND ARRAYS:
When an array is declared, compiler allocates sufficient amount of memory to contain all the
elements of the array. Base address i.e address of the first element of the array is also allocated
by the compiler.
Suppose we declare an array arr,
int arr[5] = { 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two bytes, the five
elements will be stored as follows:
11
Here variable arr will give the base address, which is a constant pointer pointing to the first
element of the array, arr[0]. Hence arr contains the address of arr[0] i.e 1000. In short, arr has
two purpose - it is the name of the array and it acts as a pointer pointing towards the first
element in the array.
arr is equal to &arr[0] by default
We can also declare a pointer of type int to point to the array arr.
int *p;
p = arr;
// or,
p = &arr[0]; //both the statements are equivalent.
Pointer to Array:
We can use a pointer to point to an array, and then we can use that pointer to access the array
elements. Lets have an example,
#include <stdio.h>
int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}
return 0;
}
In the above program, the pointer *p will print all the values stored in the array one by one. We
can also use the Base address (a in above case) to act as a pointer and print all the values.
The generalized form for using pointer with an array,
*(a+i)
is same as:
a[i]
Pointer to Multidimensional Array:
A multidimensional array is of form, a[i][j]. The name of the array gives its base address.
In a[i][j], a will give the base address of this array, even a + 0 + 0 will also give the base
address, that is the address of a[0][0] element.
Here is the generalized form for using pointer with multidimensional arrays.
*(*(a + i) + j)
12
which is same as,a[i][j]
POINTERS AND STRINGS:
Creating a string:
In the following example we are creating a string str using char character array of size 6.
char str[6] = "Hello";
The above string can be represented in memory as follows.
Each character in the string str takes 1 byte of memory space.
Creating a pointer for the string:
• The variable name of the string str holds the address of the first element of the array
i.e., it points at the starting memory address.
• So, we can create a character pointer ptr and store the address of the string str variable
in it. This way, ptr will point at the string str.
• In the following code we are assigning the address of the string str to the pointer ptr.
char *ptr = str;
We can represent the character pointer variable ptr as follows.
The pointer variable ptr is allocated memory address 8000 and it holds the address of the string
variable str i.e., 1000.
Accessing string via pointer:
To access and print the elements of the string we can use a loop and check for the 0 null
character.
Program:
13
#include <stdio.h>
int main(void)
{
char str[6] = "Hello"; // string variable
char *ptr = str; // pointer variable
while(*ptr != '0')
{
printf("%c", *ptr); // print the string
ptr++; // move the ptr pointer to the next memory location
}
return 0;
}
Using pointer to store string:
We can achieve the same result by creating a character pointer that points at a string value
stored at some memory location.
Program:
#include <stdio.h>
int main(void)
{
char *strPtr = "Hello"; // pointer variable to store string
char *t = strPtr; // temporary pointer variable
while(*t != '0')
{
printf("%c", *t); // print the string
t++; // move the t pointer to the next memory location
}
return 0;
}
• In the above image the string "Hello" is saved in the memory location 5000 to 5005.
14
• The pointer variable strPtr is at memory location 8000 and is pointing at the string
address 5000.
• The temporary variable is also assigned the address of the string so, it too holds the
value 5000 and points at the starting memory location of the string "Hello".
ARRAY OF POINTERS:
Just like we can declare an array of int, float or char etc, we can also declare an array of
pointers, here is the syntax to do the same.
Syntax:
datatype *array_name[size];
Example:
int *arrop[5];
Here arrop is an array of 5 integer pointers. It means that this array can hold the address
of 5 integer variables, or in other words, you can assign 5 pointer variables of type pointer
to int to the elements of this array.
Program:
#include<stdio.h>
#define SIZE 10
int main()
{
int *arrop[3];
int a = 10, b = 20, c = 50, i;
arrop[0] = &a;
arrop[1] = &b;
arrop[2] = &c;
for(i = 0; i < 3; i++)
{
printf("Address = %dt Value = %dn", arrop[i], *arrop[i]);
}
return 0;
}
Output:
Address = 2686764 Value = 10
Address = 2686762 Value = 20
Address = 2686760 Value = 50
arrop[i] gives the address of ith element of the array. So arrop[0] returns address of
variable a, arrop[1]returns address of b and so on. To get the value at address use indirection
operator (*).
*arrop[i]
15
So *arrop[0] gives value at address[0], Similarly *arrop[1] gives the value at
address arrop[1] and so on.
To store an array of strings:
We can create a two dimensional array and save multiple strings in it.
For example, in the given code we are storing 4 cities name in a string array city.
char city[4][12] = {
"Chennai",
"Kolkata",
"Mumbai",
"New Delhi"
};
We can represent the city array as follows.
The problem with this approach is that we are allocating 4x12 = 48 bytes memory to the city
array and we are only using 33 bytes.
We can save those unused memory spaces by using pointers as shown below.
char *cityPtr[4] = {
"Chennai",
"Kolkata",
"Mumbai",
"New Delhi"
};
In the above code we are creating an array of character pointer cityPtr of size 4 to store the
name of the four cities.
We can represent the array of pointers as follows.
The above array of pointers can be represented in memory as follows.
16
The cityPtr pointer variable is allocated the memory address 8000 to 8007. Assuming integer
address value takes 2 bytes space. So, each pointer gets 2 bytes.
Name of the cities are saved in locations 1000, 2000, 3000 and 4000.
Accessing values pointed by array of pointers:
Program:To access and print the values pointed by the array of pointers we take help of loop
#include <stdio.h>
int main(void) {
char *cityPtr[4] = {"Chennai","Kolkata","Mumbai","New Delhi"};// array of pointers
int r, c; // temporary variable
// print cities
for (r = 0; r < 4; r++) {
c = 0;
while(*(cityPtr[r] + c) != '0') {
printf("%c", *(cityPtr[r] + c));
c++;
}
printf("n");
}
return 0;
}
Output:
Chennai
Kolkata
Mumbai
New Delhi
In the above code we are using the r variable to access each row of the pointer. And we are
using the c variable to access each character in a selected row.
17
DYNAMIC MEMORY MANAGEMENT:
Dynamic memory management refers to the process of allocating memory to the variables
during execution of the program ot at run time. This allows you to obtain more memory when
required and release it when not necessary.
There are 4 library functions defined under <stdlib.h> for dynamic memory allocation.
Function Use of Function
malloc()
Allocates requested size of bytes and returns a pointer to the first byte of
allocated space
calloc()
Allocates space for an array of elements, initializes them to zero and then returns
a pointer to memory
free() deallocate the previously allocated space
realloc() Change the size of previously allocated space
malloc()
• The name malloc stands for "memory allocation".
• The function malloc() reserves a block of memory of specified size and return
a pointer of type void which can be casted into pointer of any form.
Syntax:
ptr = (cast-type*) malloc(byte-size);
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory
with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.
Example:
ptr = (int*) malloc(100 * sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively
and the pointer points to the address of first byte of memory.
Program: to find sum of n elements entered by user using malloc() and free()
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
18
ptr = (int*) malloc(num * sizeof(int)); //memory allocated using malloc
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
calloc()
• The name calloc stands for "contiguous allocation".
• The only difference between malloc() and calloc() is that, malloc() allocates single
block of memory whereas calloc() allocates multiple blocks of memory each of same
size and sets all bytes to zero.
Syntax:
ptr = (cast-type*)calloc(n, element-size);
This statement will allocate contiguous space in memory for an array of n elements.
Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of size
of float, i.e, 4 bytes.
Program: to find sum of n elements entered by user using calloc() and free
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
ptr = (int*) calloc(num, sizeof(int));
if(ptr == NULL) {
printf("Error! memory not allocated.");
19
exit(0);
}
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
free()
• Dynamically allocated memory created with either calloc() or malloc() doesn't get freed
on its own. You must explicitly use free() to release the space.
Syntax:
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
realloc()
If the previously allocated memory is insufficient or more than required, you can change the
previously allocated memory size using realloc().
Syntax:
ptr = realloc(ptr, newsize);
Here, ptr is reallocated with size of newsize.
Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Address of previously allocated memory: ");
for(i = 0; i < n1; ++i)
printf("%ut",ptr + i);
printf("nEnter new size of array: ");
20
scanf("%d", &n2);
ptr = realloc(ptr, n2);
for(i = 0; i < n2; ++i)
printf("%ut", ptr + i);
return 0;
}
PARAMETER PASSING BY ADDRESS:
In this approach, the addresses of actual arguments are passed to the function call and the
formal arguments will receive the address. Inside the function, the address is used to access
the actual argument used in the call. It means the changes made to the parameter affect the
passed argument.
Note: Actual arguments are address of the ordinary variable, pointer variable or array name.
Formal arguments should be a pointer variable or array. This approach is of practical
importance while passing arrays to functions and returning back more than one value to the
calling function. Passing arrays to functions is call by reference by default.
#include <stdio.h>
void swap(int *x, int *y);
int main ()
{
int a = 100;
int b = 200;
printf("Before swap, value of a : %dn", a );
printf("Before swap, value of b : %dn", b );
/* calling a function to swap the values.
* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b);
printf("After swap, value of a : %dn", a );
printf("After swap, value of b : %dn", b );
return 0;
}
void swap(int *x, int *y)
{
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return;
21
}
Output:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
STRUCTURES AND UNIONS
DERIVED TYPES:
A derived type is formed by using one or more basic types in combination. Using derived types,
an infinite variety of new types can be formed.There are five derived types in C:
• Function types
• Pointer types
• Array types
• Structure types
• Union types
STRUCTURES:
Arrays allow to define type of variables that can hold several data items of the same kind.
Similarly structure is another user defined data type available in C that allows to combine data
items of different kinds.
Example: Suppose you want to keep track of your books in a library. You might want to track
the following attributes about each book
Title
Author
Subject
Book ID
DEFINING A STRUCTURE:
To define a structure, you must use the struct statement. The struct statement defines a new
data type, with more than one member.
Syntax:
struct [structure tag] {
member definition;
member definition;
...
member definition;
22
} [one or more structure variables];
The structure tag is optional and each member definition is a normal variable definition, such
as int i; or float f; or any other valid variable definition. At the end of the structure's definition,
before the final semicolon, you can specify one or more structure variables but it is optional.
Example: to declare the Book structure
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
ACCESSING STRUCTURE MEMBERS:
To access any member of a structure, we use the member access operator (.). The member
access operator is coded as a period between the structure variable name and the structure
member that we wish to access.
Program:
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( ) {
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
23
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info */
printf( "Book 1 title : %sn", Book1.title);
printf( "Book 1 author : %sn", Book1.author);
printf( "Book 1 subject : %sn", Book1.subject);
printf( "Book 1 book_id : %dn", Book1.book_id);
/* print Book2 info */
printf( "Book 2 title : %sn", Book2.title);
printf( "Book 2 author : %sn", Book2.author);
printf( "Book 2 subject : %sn", Book2.subject);
printf( "Book 2 book_id : %dn", Book2.book_id);
return 0;
}
Output:
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
ARRAY OF STRUCTURES:
An array of structures is nothing but collection of structures. This is also called as structure
array in C.
This program is used to store and access “id, name and percentage” for 3 students. Structure
array is used in this program to store and display records for many students. You can store “n”
number of students record by declaring structure variable as ‘struct student record[n]“, where
n can be 1000 or 5000 etc.
#include <stdio.h>
#include <string.h>
structstudent
{
intid;
charname[30];
24
floatpercentage;
};
intmain()
{
inti;
structstudent record[2];
// 1st student's record
record[0].id=1;
strcpy(record[0].name,"Raju");
record[0].percentage=86.5;
// 2nd student's record
record[1].id=2;
strcpy(record[1].name,"Surendren");
record[1].percentage=90.5;
// 3rd student's record
record[2].id=3;
strcpy(record[2].name,"Thiyagu");
record[2].percentage=81.5;
for(i=0;i<3;i++)
{
printf(" Records of STUDENT : %d n",i+1);
printf(" Id is: %d n",record[i].id);
printf(" Name is: %s n",record[i].name);
printf(" Percentage is: %fnn",record[i].percentage);
}
return0;
}
Output:
Records of STUDENT : 1
Id is: 1
Name is: Raju
Percentage is: 86.500000
Records of STUDENT : 2
Id is: 2
25
Name is: Surendren
Percentage is: 90.500000
Records of STUDENT : 3
Id is: 3
Name is: Thiyagu
Percentage is: 81.500000
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.
• In other words, structures pointing to the same type of structures are self-referential in
nature.
• A self-referential structure is used to create data structures like linked lists, stacks, etc.
Syntax:
struct struct_name
{
datatype datatypename;
struct_name *pointer_name;
};
Self-referential Structure with Single Link:
These structures can have only one self-pointer as their member. The following example will
show us how to connect the objects of a self-referential structure with the single link and
accessthe corresponding data members. The connection formed is shown in the following
figure.
10 20
ob1 ob2
Program:
#include <stdio.h>
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
30 40 X
26
struct node ob1; // Node1
// Intialization
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;
struct node ob2; // Node2
// Initialization
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;
// Linking ob1 and ob2
ob1.link = &ob2;
// Accessing data members of ob2 using ob1
printf("%d", ob1.link->data1);
printf("n%d", ob1.link->data2);
return 0;
}
Output:
30
40
UNIONS:
A union is a special data type available in C that allows to store different data types in the same
memory location. You can define a union with many members, but only one member can
contain a value at any given time. Unions provide an efficient way of using the same memory
location for multiple-purpose.
Defining a Union:
To define a union, you must use the union statement in the same way as you did while defining
a structure. The union statement defines a new data type with more than one member for your
program.
Syntax:
union [union tag] {
member definition;
member definition;
27
...
member definition;
} [one or more union variables];
The union tag is optional and each member definition is a normal variable definition, such as
int i; or float f; or any other valid variable definition. At the end of the union's definition, before
the final semicolon, you can specify one or more union variables but it is optional.
Example:
union Data {
int i;
float f;
char str[20];
} data;
Now, a variable of ‘Data’ type can store an integer, a floating-point number, or a string of
characters. It means a single variable, i.e., same memory location, can be used to store multiple
types of data.
The memory occupied by a union will be large enough to hold the largest member of the union.
For example, in the above example, Data type will occupy 20 bytes of memory space because
this is the maximum space which can be occupied by a character string. The following example
displays the total memory size occupied by the above union:
Program:
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
printf( "Memory size occupied by data : %dn", sizeof(data));
return 0;
}
Output:
Memory size occupied by data : 20
Accessing Union Members:
28
To access any member of a union, we use the member access operator (.). The member access
operator is coded as a period between the union variable name and the union member that we
wish to access. You would use the keyword union to define variables of union type.
Program:
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %dn", data.i);
printf( "data.f : %fn", data.f);
printf( "data.str : %sn", data.str);
return 0;
}
Output:
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Here, we can see that the values of i and f members of union got corrupted because the final
value assigned to the variable has occupied the memory location and this is the reason that the
value of str member is getting printed very well.
Program:
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
29
int main( ) {
union Data data;
data.i = 10;
printf( "data.i : %dn", data.i);
data.f = 220.5;
printf( "data.f : %fn", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %sn", data.str);
return 0;
}
Output:
data.i : 10
data.f : 220.500000
data.str : C Programming
Here, all the members are getting printed very well because one member is being used at a tim
DATA FILES
In C programming, file is a place on your physical disk where information is stored.
WHY FILES ARE NEEDED?
• When a program is terminated, the entire data is lost. Storing in a file will preserve your
data even if the program terminates.
• If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents
of the file using few commands in C.
• You can easily move your data from one computer to another without any changes.
TYPES OF FILES:
When dealing with files, there are two types of files you should know about:
• Text files
• Binary files
Text files:
• Text files are the normal .txt files that you can easily create using Notepad or any simple
text editors.
• When you open those files, you'll see all the contents within the file as plain text. You
can easily edit or delete the contents.
• They take minimum effort to maintain, are easily readable, and provide least security
and takes bigger storage space.
30
Binary files:
• Binary files are mostly the .bin files in your computer.
• Instead of storing data in plain text, they store it in the binary form (0's and 1's).
• They can hold higher amount of data, are not readable easily and provides a better
security than text files.
C provides a number of functions that helps to perform basic file operations. Following are
the functions,
Function description
fopen() create a new file or open a existing file
fclose() closes a file
getc() reads a character from a file
putc() writes a character to a file
fscanf() reads a set of data from a file
fprintf() writes a set of data to a file
getw() reads a integer from a file
putw() writes a integer to a file
fseek() set the position to desire point
ftell() gives current position in the file
rewind() set the position to the begining point
FILE OPERATIONS:
In C, you can perform four major operations on the file, either text or binary:
• Creating a new file
• Opening an existing file
• Closing a file
• Reading from and writing information to a file
DECLARATION:
When working with files, you need to declare a pointer of type file. This declaration is needed
for communication between the file and program.
FILE *fptr;
OPENING A FILE - FOR CREATION AND EDIT:
Opening a file is performed using the library function in the "stdio.h" header file: fopen().
Syntax:
fptr=fopen(const char *filename, const char *mode);
31
Example:
fopen("E:cprogramnewprogram.txt","w");
fopen("E:cprogramoldprogram.bin","rb");
• Let's suppose the file newprogram.txt doesn't exist in the location E:cprogram. The
first function creates a new file named newprogram.txt and opens it for writing as per
the mode 'w'.The writing mode allows you to create and edit (overwrite) the contents
of the file.
• Now let's suppose the second binary file oldprogram.bin exists in the
location E:cprogram. The second function opens the existing file for reading in binary
mode 'rb'. The reading mode only allows you to read the file, you cannot write into the
file.
OPENING MODES IN STANDARD I/O:
File
Mode
Meaning of Mode During Inexistence of file
R Open for reading.
If the file does not exist, fopen() returns
NULL.
Rb Open for reading in binary mode.
If the file does not exist, fopen() returns
NULL.
W Open for writing.
If the file exists, its contents are
overwritten. If the file does not exist, it will
be created.
wb Open for writing in binary mode.
If the file exists, its contents are
overwritten. If the file does not exist, it will
be created.
A
Open for append. i.e, Data is
added to end of file.
If the file does not exists, it will be created.
32
File
Mode
Meaning of Mode During Inexistence of file
Ab
Open for append in binary mode.
i.e, Data is added to end of file.
If the file does not exists, it will be created.
r+
Open for both reading and
writing.
If the file does not exist, fopen() returns
NULL.
rb+
Open for both reading and
writing in binary mode.
If the file does not exist, fopen() returns
NULL.
w+
Open for both reading and
writing.
If the file exists, its contents are
overwritten. If the file does not exist, it will
be created.
wb+
Open for both reading and
writing in binary mode.
If the file exists, its contents are
overwritten. If the file does not exist, it will
be created.
a+
Open for both reading and
appending.
If the file does not exists, it will be created.
ab+
Open for both reading and
appending in binary mode.
If the file does not exists, it will be created.
CLOSING A FILE:
The file (both text and binary) should be closed after reading/writing.Closing a file is
performed using library function fclose().
Syntax:
fclose(fptr); //fptr is the file pointer associated with file to be closed.
READING AND WRITING TO A TEXT FILE:
For reading and writing to a text file, we use the functions fprintf() and fscanf().They are just
the file versions of printf() and scanf(). The only difference is that, fprint and fscanf expects a
pointer to the structure FILE.
Program: Write to a text file using fprintf()
#include<stdio.h>
33
#include<conio.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen("C:program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}
Output:
This program takes a number from user and stores in the file program.txt.
After you compile and run this program, you can see a text file program.txt created in C drive
of your computer. When you open the file, you can see the integer you entered.
Program: Read from a text file using fscanf()
#include <stdio.h>
#include <conio.h>
int main()
{
int num;
FILE *fptr;
if ((fptr = fopen("C:program.txt","r")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
fscanf(fptr,"%d", &num);
printf("Value of n=%d", num);
fclose(fptr);
return 0;
}
34
Output:
This program reads the integer present in the program.txt file and prints it onto the screen.
If you succesfully created the file from Example 1, running this program will get you the
integer you entered.
Other functions like fgetchar(), fputc() etc. can be used in similar way.
feof():
Check end-of-file indicator Checks whether the end-of-File indicator associated with stream is
set, returning a value different from zero if it is.This indicator is generally set by a previous
operation on the stream that attempted to read at or past the end-of-file.
Program:to open a file and to print it contents on screen.
#include <stdio.h>
#include <conio.h>
void main()
{
FILE *fp;
char s;
clrscr();
fp=fopen("source.txt","r");
if(fp==NULL)
{
printf("nCAN NOT OPEN FILE");
getch();
exit();
}
do
{
s=getc(fp);
printf("%c",s);
} while(s!=EOF);
fclose(fp);
getch();
}
Program:to copy files
#include<stdio.h>
void main()
{
FILE *fp1,*fp2;
char ch;
fp1=fopen("source.txt","r");
if(fp1==NULL)
{
puts("Cannot open this file");
35
exit(1);
}
fp2=fopen("destination.txt", "w");
if(fp2==NULL)
{
puts("Not able to open this file");
fclose(fp1);
exit(1);
}
while((ch = fgetc(fp1))!= EOF)
{
fputc(ch,fp2);
}
printf("File copied successfully");
fclose(fp2);
fclose(fp1);
}
Program:to merge two files and store the contents in another file
#include <stdio.h>
void main()
{
FILE *fp1, *fp2, *fp;
char ch;
clrscr();
fp1=fopen(sample1.txt,"r");
fp2=fopen(sample2.txt,"r");
if(fp1== NULL||fp2==NULL)
{
perror("Error");
printf("Press any key to exit...n");
getch();
exit(0);
}
fp=fopen(mergefile.txt,"w");
if(fp==NULL)
{
perror("Error ");
printf("Press any key to exit...n");
exit(0);
}
while((ch=fgetc(fp1))!=EOF)
{
fputc(ch,fp);
}
while((ch=fgetc(fp2))!=EOF)
{
fputc(ch,fp);
36
}
printf("Two files were merged into %s file successfully.n",mergefile.txt);
fclose(fp1);
fclose(fp2);
fclose(fp);
getch();
}
Program:to delete a file
#include<stdio.h>
#include<conio.h>
#include<process.h>
main()
{
FILE *fp;
char filename[20];
int status;
clrscr();
printf("nEnter the file name: ");
scanf("%s",filename);
fp = fopen(filename, r);
if(fp == NULL)
{
printf("Error: file not found! check the directory!!nn");
exit(0);
}
fclose(fp);
status = remove(file_name);
if( status == 0 )
printf("%s file deleted successfully.n",file_name);
else
{
printf("Unable to delete the filen");
perror("Error");
}
return 0;
}
Program:to count the number of characters and number of lines in a file.
#include <stdio.h>
int main()
{
FILE *fp;
int countl=1; // Line counter
int countc=0; // Characters counter
char filename[50];
char ch; // To store a character read from file
// Get file name from user. The file should be
37
// either in current folder or complete path should be provided
printf("Enter file name: ");//Extension is also required
scanf("%s", filename);
// Open the file
fp = fopen(filename, "r"); // Check if file exists
if (fp == NULL)
{
printf("Could not open file %s", filename);
exit(1);
}
// Extract characters from file and store in character ch
while((ch=getc(fp))!=EOF)
{
countc++;
if(ch=='n')
countl++;
}
// Close the file
fclose(fp);
printf("The file %s has %d characters and %d lines ", filename,countc,countl);
getch();
return 0;
}
Output:
Enter file name:test.txt
The file test.txt has 20 characters and 3 lines

More Related Content

Similar to Pointers, Structures, Unions and Data Files in C

Similar to Pointers, Structures, Unions and Data Files in C (20)

Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programming
 
Pointers
PointersPointers
Pointers
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
 
Pointers
PointersPointers
Pointers
 
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdfEASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
 
Pointer.pptx
Pointer.pptxPointer.pptx
Pointer.pptx
 
Arrays to arrays and pointers with arrays.pptx
Arrays to arrays and pointers with arrays.pptxArrays to arrays and pointers with arrays.pptx
Arrays to arrays and pointers with arrays.pptx
 
FYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxFYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptx
 
Ponters
PontersPonters
Ponters
 
4 Pointers.pptx
4 Pointers.pptx4 Pointers.pptx
4 Pointers.pptx
 
PPS-POINTERS.pptx
PPS-POINTERS.pptxPPS-POINTERS.pptx
PPS-POINTERS.pptx
 
Advanced pointers
Advanced pointersAdvanced pointers
Advanced pointers
 
C Programming Unit-4
C Programming Unit-4C Programming Unit-4
C Programming Unit-4
 
Pointer introduction day1
Pointer introduction day1Pointer introduction day1
Pointer introduction day1
 
Presentation on pointer.
Presentation on pointer.Presentation on pointer.
Presentation on pointer.
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
C pointer
C pointerC pointer
C pointer
 
VIT351 Software Development VI Unit3
VIT351 Software Development VI Unit3VIT351 Software Development VI Unit3
VIT351 Software Development VI Unit3
 
Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad Salman
 
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdfPOINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
 

Recently uploaded

Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 

Recently uploaded (20)

Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 

Pointers, Structures, Unions and Data Files in C

  • 1. 1 UNIT - V POINTERS, STRUCTURES & UNIONS, DATA FILES Pointers: Concept of a Pointer, Initialization of pointer variables, pointers as function arguments, address arithmetic, pointers to pointers, Pointers and arrays, Array of Pointers, Dynamic memory management functions, parameter passing by address. Structures and Unions: Structures declaration, Initialization of structures, accessing structures,unions Data Files: Declaring, Opening, and Closing File Streams, Reading from and Writing to Text Files. S.NO TOPIC PAGE NUMBER 1. Pointer declaration & Initialization 2 2. Pointer as function argument 4 3. NULL pointer 3 4. Generic or void pointer 4 5. Address arithmetic 6 6. Pointer to pointer(or)double pointer 9 7. Pointer and arrays 10 8. Array of pointer 13 9. Dynamic memory allocation 16 10. Parameter passing techniques 19 11. Structure declaration& initialization 20 12. Accessing of structure elements 21 13. Array of structures 22 14. Union 25 15. Declaration of file 28 16. Opening a file 29 17. Closing a file 31 18. Reading from and writing into text file 31
  • 2. 2 ADDRESS IN C: If you have a variable ‘var’ in your program, ‘&var’ will give you its address in the memory, where & is commonly called the reference operator. This notation is seen in the scanf function. It is used in the function to store the user inputted value in the address of var. scanf("%d", &var); Program: #include <stdio.h> int main() { int var = 5; printf("Value: %dn", var); printf("Address: %u", &var); //Notice, the ampersand(&) before var. return 0; } Output: Value: 5 Address: 2686778 POINTERS: A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address. Declaration: data_type *var-name; Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer variable. Examples: int *ip; /* pointer to an integer */ double *dp; /* pointer to a double */ float *fp; /* pointer to a float */ char *ch /* pointer to a character */ Initialization of pointer variable: The initialization of a pointer variable is similar to other variable initialization, but in the pointer variable we assign the address instead of value. int *ptr, var;
  • 3. 3 ptr = &var; In the above example we have a pointer variable (*ptr) and a simple integer variable (var). We have to assign the pointer variable to the address of ‘var’. It means that the pointer variable ‘*ptr’ now has the address of the variable ‘var’. REFERENCE OPERATOR (&) AND DEREFERENCE OPERATOR (*): &is called reference operator which gives the address of a variable.Likewise, there is another operator that gets you the value from the address, it is called a dereference operator (*).Note: The * sign when declaring a pointer is not a dereference operator. Program: #include <stdio.h> int main(){ int *pc; int c; c=22; printf("Address of c:%un",&c); printf("Value of c:%dn",c); pc=&c; printf("Address of pointer pc:%un",pc); printf("Content of pointer pc:%dn",*pc); c=11; printf("Address of pointer pc:%un",pc); printf("Content of pointer pc:%dn",*pc); *pc=2; printf("Address of c:%un",&c); printf("Value of c:%dn",c); return 0; } Output: Address of c: 2686784 Value of c: 22 Address of pointer pc: 2686784 Content of pointer pc: 22 Address of pointer pc: 2686784 Content of pointer pc: 11 Address of c: 2686784 Value of c: 2
  • 4. 4 NULL POINTERS: It is always a good practice to assign a NULL value to a pointer variable in case you do not have an exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a nullpointer. #include <stdio.h> int main () { int *ptr = NULL; printf("The value of ptr is : %xn", ptr ); return 0; } Output: The value of ptr is 0 GENERIC POINTERS: It is a pointer variable that has void as its data type. It can be used to point to variables of any type. void *ptr; In C, since we cannot have a variable of type void, the void pointer will therefore not point to any data and thus cannot be dereferenced. We need to typecast a void pointer to another kind of pointer before using it. It is often used when we want a pointer to point to data of different types at different time. #include <stdio.h> int main () { int x=10; void *ptr; ptr = &x; printf(“generic pointer points to the integer value %d”, *(int*)ptr); return 0; } Output: Generic pointer points to the integer value 10 POINTERS AS FUNCTION ARGUMENTS: C programming allows passing a pointer to a function. To do so, simply declare the function parameter as a pointer type and send the addresses of the variables in the function call. Program: to swap two numbers using pointers and function. #include <stdio.h> void swap(int *n1, int *n2); int main() {
  • 5. 5 int num1 = 5, num2 = 10; swap( &num1, &num2); // address of num1 and num2 is passed to the swap function printf("Number1 = %dn", num1); printf("Number2 = %d", num2); return 0; } void swap(int * n1, int * n2) { // pointer n1 and n2 points to the address of num1 and num2 respectively int temp; temp = *n1; *n1 = *n2; *n2 = temp; } Output: Number1 = 10 Number2 = 5 • The address of memory location num1 and num2 are passed to the function swap and the pointers *n1 and *n2 accept those values. • So, now the pointer n1 and n2 points to the address of num1 and num2 respectively. • When, the value of pointers are changed, the value in the pointed memory location also changes correspondingly. • Hence, changes made to *n1 and *n2 are reflected in num1 and num2 in the main function. • This technique is known as Call by Reference in C programming. DANGLING POINTERS: • Dangling pointers arise when an object is deleted or de-allocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the de- allocated memory. • In short pointer pointing to non-existing memory location is called dangling pointer. Examples: Way 1 : Using free or de-allocating memory #include<stdlib.h> { char *ptr = malloc(Constant_Value); ....... .......
  • 6. 6 ....... free (ptr); /* ptr now becomes a dangling pointer */ } We have declared the character pointer in the first step. After execution of some statements we have de-allocated memory which is allocated previously for the pointer. As soon as memory is de-allocated for pointer, pointer becomes dangling pointer How to Ensure that Pointer is no Longer Dangling ? #include<stdlib.h> { char *ptr = malloc(Constant_Value); ....... ....... ....... free (ptr); /* ptr now becomes a dangling pointer */ ptr = NULL /* ptr is no more dangling pointer */ } After de-allocating memory, initialize pointer to NULL so that pointer will be no longer dangling. Assigning NULL value means pointer is not pointing to any memory location Way 2 :Out of Scope #include<stdlib.h> void main() { char *ptr; ..... ..... { char ch; ptr = &ch; } ..... } Character pointer is declared in the first step. Pointer variable ‘ptr’ is pointing to character variable ‘ch’ declared in the inner block . As character variable is non-visible in outer block, then pointer is still pointing to same invalid memory location in outer block , then pointer becomes “dangling”.
  • 7. 7 POINTER ARITHMETIC: A pointer in C is an address, which is a numeric value. Therefore, you can perform arithmetic operations on a pointer just as you can on a numeric value. There are the arithmetic operators that can be used on pointers: ++, --. To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to the address 1000. Let us perform the following arithmetic operation on the pointer – ptr++ After the above operation, the ptr will point to the location 1002 because each time ptr is incremented, it will point to the next integer location which is 2 bytes next to the current location. If ptr points to a character whose address is 1000, then the above operation will point to the location 1001 because the next character will be available at 1001. Incrementing a Pointer: Program: to increment the variable pointer to access each succeeding element of the array #include <stdio.h> const int MAX = 3; int main () { int var[] = {10, 100, 200}; int i, *ptr; /* let us have array address in pointer */ ptr = var; for ( i = 0; i < MAX; i++) { printf("Address of var[%d] = %xn", i, ptr ); printf("Value of var[%d] = %dn", i, *ptr ); ptr++; /* move to the next location */ } return 0; } Output: Address of var[0] = bf882b30 Value of var[0] = 10 Address of var[1] = bf882b32 Value of var[1] = 100 Address of var[2] = bf882b34 Value of var[2] = 200 Decrementing a Pointer: Program: #include <stdio.h> const int MAX = 3;
  • 8. 8 int main () { int var[] = {10, 100, 200}; int i, *ptr; ptr = &var[MAX-1]; /* let us have array address in pointer */ for ( i = MAX; i > 0; i--) { printf("Address of var[%d] = %xn", i-1, ptr ); printf("Value of var[%d] = %dn", i-1, *ptr ); ptr--; /* move to the previous location */ } return 0; } Output: Address of var[2] = bfedbcd8 Value of var[2] = 200 Address of var[1] = bfedbcd6 Value of var[1] = 100 Address of var[0] = bfedbcd4 Value of var[0] = 10 CHARACTER POINTERS: Consider the following example: char arr[] = "Hello World"; // array version char ptr* = "Hello World"; // pointer version Similarity between them: The type of variable is a pointer to char or (char*), so you can pass either of them to a function whose formal argument accepts an array of characters or a character pointer. Difference between them: arr is an array of 12 characters. When compiler sees the statement: char arr[] = "Hello World"; It allocates 12 consecutive bytes of memory and associates the address of the first allocated byte with arr. On the other hand when the compiler sees the statement. char ptr* = "Hello World"; It allocates 12 consecutive bytes for string literal "Hello World" and 2 extra bytes for pointer variable ptr. And assigns the address of the string literal to ptr. So, in this case, a total of 14 bytes are allocated.
  • 9. 9 After the above assignment, ptr points to the address of "Hello World" which is stored somewhere in the memory. How do we assign a different string to arr ? We can assign a new string to arr by using gets(), scanf(), strcpy() or by assigning characters one by one. Example: gets(arr); scanf("%s", arr); strcpy(arr, "new string"); arr[0] = 'R'; arr[1] = 'e'; arr[2] = 'd'; arr[3] = ' '; arr[4] = 'D'; arr[5] = 'r'; arr[6] = 'a'; arr[7] = 'g'; arr[8] = 'o'; arr[9] = 'n'; Modifying a string literal causes undefined behavior, so the following operations are invalid. char *ptr = "Hello"; ptr[0] = 'Y'; or *ptr = 'Y'; gets(name); scanf("%s", ptr); strcpy(ptr, "source"); strcat(ptr, "second string"); Using an uninitialized pointer may also lead to undefined undefined behavior. char *ptr; Here ptr is uninitialized an contains garbage value. So the following operations are invalid. ptr[0] = 'H'; gets(ptr); scanf("%s", ptr); strcpy(ptr, "source"); strcat(ptr, "second string"); We can only use ptr only if it points to a valid memory location. char str[10]; char *p = str; Now all the operations mentioned above are valid.
  • 10. 10 POINTER TO POINTERS: A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below. Declaration: int **var; //declares a pointer to pointer of type int When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the asterisk operator be applied twice, as is shown below in the example: Program: #include <stdio.h> int main () { int var; int *ptr; int **pptr; var = 3000; ptr = &var; /* take the address of var */ pptr = &ptr; /* take the address of ptr using address of operator & */ printf("Value of var = %dn", var ); /* take the value using pptr */ printf("Value available at *ptr = %dn", *ptr ); printf("Value available at **pptr = %dn", **pptr); return 0; } Output: Value of var = 3000 Value available at *ptr = 3000 Value available at **pptr = 3000 POINTERS AND ARRAYS: When an array is declared, compiler allocates sufficient amount of memory to contain all the elements of the array. Base address i.e address of the first element of the array is also allocated by the compiler. Suppose we declare an array arr, int arr[5] = { 1, 2, 3, 4, 5 }; Assuming that the base address of arr is 1000 and each integer requires two bytes, the five elements will be stored as follows:
  • 11. 11 Here variable arr will give the base address, which is a constant pointer pointing to the first element of the array, arr[0]. Hence arr contains the address of arr[0] i.e 1000. In short, arr has two purpose - it is the name of the array and it acts as a pointer pointing towards the first element in the array. arr is equal to &arr[0] by default We can also declare a pointer of type int to point to the array arr. int *p; p = arr; // or, p = &arr[0]; //both the statements are equivalent. Pointer to Array: We can use a pointer to point to an array, and then we can use that pointer to access the array elements. Lets have an example, #include <stdio.h> int main() { int i; int a[5] = {1, 2, 3, 4, 5}; int *p = a; // same as int*p = &a[0] for (i = 0; i < 5; i++) { printf("%d", *p); p++; } return 0; } In the above program, the pointer *p will print all the values stored in the array one by one. We can also use the Base address (a in above case) to act as a pointer and print all the values. The generalized form for using pointer with an array, *(a+i) is same as: a[i] Pointer to Multidimensional Array: A multidimensional array is of form, a[i][j]. The name of the array gives its base address. In a[i][j], a will give the base address of this array, even a + 0 + 0 will also give the base address, that is the address of a[0][0] element. Here is the generalized form for using pointer with multidimensional arrays. *(*(a + i) + j)
  • 12. 12 which is same as,a[i][j] POINTERS AND STRINGS: Creating a string: In the following example we are creating a string str using char character array of size 6. char str[6] = "Hello"; The above string can be represented in memory as follows. Each character in the string str takes 1 byte of memory space. Creating a pointer for the string: • The variable name of the string str holds the address of the first element of the array i.e., it points at the starting memory address. • So, we can create a character pointer ptr and store the address of the string str variable in it. This way, ptr will point at the string str. • In the following code we are assigning the address of the string str to the pointer ptr. char *ptr = str; We can represent the character pointer variable ptr as follows. The pointer variable ptr is allocated memory address 8000 and it holds the address of the string variable str i.e., 1000. Accessing string via pointer: To access and print the elements of the string we can use a loop and check for the 0 null character. Program:
  • 13. 13 #include <stdio.h> int main(void) { char str[6] = "Hello"; // string variable char *ptr = str; // pointer variable while(*ptr != '0') { printf("%c", *ptr); // print the string ptr++; // move the ptr pointer to the next memory location } return 0; } Using pointer to store string: We can achieve the same result by creating a character pointer that points at a string value stored at some memory location. Program: #include <stdio.h> int main(void) { char *strPtr = "Hello"; // pointer variable to store string char *t = strPtr; // temporary pointer variable while(*t != '0') { printf("%c", *t); // print the string t++; // move the t pointer to the next memory location } return 0; } • In the above image the string "Hello" is saved in the memory location 5000 to 5005.
  • 14. 14 • The pointer variable strPtr is at memory location 8000 and is pointing at the string address 5000. • The temporary variable is also assigned the address of the string so, it too holds the value 5000 and points at the starting memory location of the string "Hello". ARRAY OF POINTERS: Just like we can declare an array of int, float or char etc, we can also declare an array of pointers, here is the syntax to do the same. Syntax: datatype *array_name[size]; Example: int *arrop[5]; Here arrop is an array of 5 integer pointers. It means that this array can hold the address of 5 integer variables, or in other words, you can assign 5 pointer variables of type pointer to int to the elements of this array. Program: #include<stdio.h> #define SIZE 10 int main() { int *arrop[3]; int a = 10, b = 20, c = 50, i; arrop[0] = &a; arrop[1] = &b; arrop[2] = &c; for(i = 0; i < 3; i++) { printf("Address = %dt Value = %dn", arrop[i], *arrop[i]); } return 0; } Output: Address = 2686764 Value = 10 Address = 2686762 Value = 20 Address = 2686760 Value = 50 arrop[i] gives the address of ith element of the array. So arrop[0] returns address of variable a, arrop[1]returns address of b and so on. To get the value at address use indirection operator (*). *arrop[i]
  • 15. 15 So *arrop[0] gives value at address[0], Similarly *arrop[1] gives the value at address arrop[1] and so on. To store an array of strings: We can create a two dimensional array and save multiple strings in it. For example, in the given code we are storing 4 cities name in a string array city. char city[4][12] = { "Chennai", "Kolkata", "Mumbai", "New Delhi" }; We can represent the city array as follows. The problem with this approach is that we are allocating 4x12 = 48 bytes memory to the city array and we are only using 33 bytes. We can save those unused memory spaces by using pointers as shown below. char *cityPtr[4] = { "Chennai", "Kolkata", "Mumbai", "New Delhi" }; In the above code we are creating an array of character pointer cityPtr of size 4 to store the name of the four cities. We can represent the array of pointers as follows. The above array of pointers can be represented in memory as follows.
  • 16. 16 The cityPtr pointer variable is allocated the memory address 8000 to 8007. Assuming integer address value takes 2 bytes space. So, each pointer gets 2 bytes. Name of the cities are saved in locations 1000, 2000, 3000 and 4000. Accessing values pointed by array of pointers: Program:To access and print the values pointed by the array of pointers we take help of loop #include <stdio.h> int main(void) { char *cityPtr[4] = {"Chennai","Kolkata","Mumbai","New Delhi"};// array of pointers int r, c; // temporary variable // print cities for (r = 0; r < 4; r++) { c = 0; while(*(cityPtr[r] + c) != '0') { printf("%c", *(cityPtr[r] + c)); c++; } printf("n"); } return 0; } Output: Chennai Kolkata Mumbai New Delhi In the above code we are using the r variable to access each row of the pointer. And we are using the c variable to access each character in a selected row.
  • 17. 17 DYNAMIC MEMORY MANAGEMENT: Dynamic memory management refers to the process of allocating memory to the variables during execution of the program ot at run time. This allows you to obtain more memory when required and release it when not necessary. There are 4 library functions defined under <stdlib.h> for dynamic memory allocation. Function Use of Function malloc() Allocates requested size of bytes and returns a pointer to the first byte of allocated space calloc() Allocates space for an array of elements, initializes them to zero and then returns a pointer to memory free() deallocate the previously allocated space realloc() Change the size of previously allocated space malloc() • The name malloc stands for "memory allocation". • The function malloc() reserves a block of memory of specified size and return a pointer of type void which can be casted into pointer of any form. Syntax: ptr = (cast-type*) malloc(byte-size); Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer. Example: ptr = (int*) malloc(100 * sizeof(int)); This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the pointer points to the address of first byte of memory. Program: to find sum of n elements entered by user using malloc() and free() #include <stdio.h> #include <stdlib.h> int main() { int num, i, *ptr, sum = 0; printf("Enter number of elements: "); scanf("%d", &num);
  • 18. 18 ptr = (int*) malloc(num * sizeof(int)); //memory allocated using malloc if(ptr == NULL) { printf("Error! memory not allocated."); exit(0); } printf("Enter elements of array: "); for(i = 0; i < num; ++i) { scanf("%d", ptr + i); sum += *(ptr + i); } printf("Sum = %d", sum); free(ptr); return 0; } calloc() • The name calloc stands for "contiguous allocation". • The only difference between malloc() and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero. Syntax: ptr = (cast-type*)calloc(n, element-size); This statement will allocate contiguous space in memory for an array of n elements. Example: ptr = (float*) calloc(25, sizeof(float)); This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e, 4 bytes. Program: to find sum of n elements entered by user using calloc() and free #include <stdio.h> #include <stdlib.h> int main() { int num, i, *ptr, sum = 0; printf("Enter number of elements: "); scanf("%d", &num); ptr = (int*) calloc(num, sizeof(int)); if(ptr == NULL) { printf("Error! memory not allocated.");
  • 19. 19 exit(0); } printf("Enter elements of array: "); for(i = 0; i < num; ++i) { scanf("%d", ptr + i); sum += *(ptr + i); } printf("Sum = %d", sum); free(ptr); return 0; } free() • Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its own. You must explicitly use free() to release the space. Syntax: free(ptr); This statement frees the space allocated in the memory pointed by ptr. realloc() If the previously allocated memory is insufficient or more than required, you can change the previously allocated memory size using realloc(). Syntax: ptr = realloc(ptr, newsize); Here, ptr is reallocated with size of newsize. Program: #include <stdio.h> #include <stdlib.h> int main() { int *ptr, i , n1, n2; printf("Enter size of array: "); scanf("%d", &n1); ptr = (int*) malloc(n1 * sizeof(int)); printf("Address of previously allocated memory: "); for(i = 0; i < n1; ++i) printf("%ut",ptr + i); printf("nEnter new size of array: ");
  • 20. 20 scanf("%d", &n2); ptr = realloc(ptr, n2); for(i = 0; i < n2; ++i) printf("%ut", ptr + i); return 0; } PARAMETER PASSING BY ADDRESS: In this approach, the addresses of actual arguments are passed to the function call and the formal arguments will receive the address. Inside the function, the address is used to access the actual argument used in the call. It means the changes made to the parameter affect the passed argument. Note: Actual arguments are address of the ordinary variable, pointer variable or array name. Formal arguments should be a pointer variable or array. This approach is of practical importance while passing arrays to functions and returning back more than one value to the calling function. Passing arrays to functions is call by reference by default. #include <stdio.h> void swap(int *x, int *y); int main () { int a = 100; int b = 200; printf("Before swap, value of a : %dn", a ); printf("Before swap, value of b : %dn", b ); /* calling a function to swap the values. * &a indicates pointer to a ie. address of variable a and * &b indicates pointer to b ie. address of variable b. */ swap(&a, &b); printf("After swap, value of a : %dn", a ); printf("After swap, value of b : %dn", b ); return 0; } void swap(int *x, int *y) { int temp; temp = *x; /* save the value at address x */ *x = *y; /* put y into x */ *y = temp; /* put temp into y */ return;
  • 21. 21 } Output: Before swap, value of a :100 Before swap, value of b :200 After swap, value of a :200 After swap, value of b :100 STRUCTURES AND UNIONS DERIVED TYPES: A derived type is formed by using one or more basic types in combination. Using derived types, an infinite variety of new types can be formed.There are five derived types in C: • Function types • Pointer types • Array types • Structure types • Union types STRUCTURES: Arrays allow to define type of variables that can hold several data items of the same kind. Similarly structure is another user defined data type available in C that allows to combine data items of different kinds. Example: Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book Title Author Subject Book ID DEFINING A STRUCTURE: To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member. Syntax: struct [structure tag] { member definition; member definition; ... member definition;
  • 22. 22 } [one or more structure variables]; The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure's definition, before the final semicolon, you can specify one or more structure variables but it is optional. Example: to declare the Book structure struct Books { char title[50]; char author[50]; char subject[100]; int book_id; } book; ACCESSING STRUCTURE MEMBERS: To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. Program: #include <stdio.h> #include <string.h> struct Books { char title[50]; char author[50]; char subject[100]; int book_id; }; int main( ) { struct Books Book1; /* Declare Book1 of type Book */ struct Books Book2; /* Declare Book2 of type Book */ /* book 1 specification */ strcpy( Book1.title, "C Programming"); strcpy( Book1.author, "Nuha Ali"); strcpy( Book1.subject, "C Programming Tutorial"); Book1.book_id = 6495407; /* book 2 specification */ strcpy( Book2.title, "Telecom Billing");
  • 23. 23 strcpy( Book2.author, "Zara Ali"); strcpy( Book2.subject, "Telecom Billing Tutorial"); Book2.book_id = 6495700; /* print Book1 info */ printf( "Book 1 title : %sn", Book1.title); printf( "Book 1 author : %sn", Book1.author); printf( "Book 1 subject : %sn", Book1.subject); printf( "Book 1 book_id : %dn", Book1.book_id); /* print Book2 info */ printf( "Book 2 title : %sn", Book2.title); printf( "Book 2 author : %sn", Book2.author); printf( "Book 2 subject : %sn", Book2.subject); printf( "Book 2 book_id : %dn", Book2.book_id); return 0; } Output: Book 1 title : C Programming Book 1 author : Nuha Ali Book 1 subject : C Programming Tutorial Book 1 book_id : 6495407 Book 2 title : Telecom Billing Book 2 author : Zara Ali Book 2 subject : Telecom Billing Tutorial Book 2 book_id : 6495700 ARRAY OF STRUCTURES: An array of structures is nothing but collection of structures. This is also called as structure array in C. This program is used to store and access “id, name and percentage” for 3 students. Structure array is used in this program to store and display records for many students. You can store “n” number of students record by declaring structure variable as ‘struct student record[n]“, where n can be 1000 or 5000 etc. #include <stdio.h> #include <string.h> structstudent { intid; charname[30];
  • 24. 24 floatpercentage; }; intmain() { inti; structstudent record[2]; // 1st student's record record[0].id=1; strcpy(record[0].name,"Raju"); record[0].percentage=86.5; // 2nd student's record record[1].id=2; strcpy(record[1].name,"Surendren"); record[1].percentage=90.5; // 3rd student's record record[2].id=3; strcpy(record[2].name,"Thiyagu"); record[2].percentage=81.5; for(i=0;i<3;i++) { printf(" Records of STUDENT : %d n",i+1); printf(" Id is: %d n",record[i].id); printf(" Name is: %s n",record[i].name); printf(" Percentage is: %fnn",record[i].percentage); } return0; } Output: Records of STUDENT : 1 Id is: 1 Name is: Raju Percentage is: 86.500000 Records of STUDENT : 2 Id is: 2
  • 25. 25 Name is: Surendren Percentage is: 90.500000 Records of STUDENT : 3 Id is: 3 Name is: Thiyagu Percentage is: 81.500000 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. • In other words, structures pointing to the same type of structures are self-referential in nature. • A self-referential structure is used to create data structures like linked lists, stacks, etc. Syntax: struct struct_name { datatype datatypename; struct_name *pointer_name; }; Self-referential Structure with Single Link: These structures can have only one self-pointer as their member. The following example will show us how to connect the objects of a self-referential structure with the single link and accessthe corresponding data members. The connection formed is shown in the following figure. 10 20 ob1 ob2 Program: #include <stdio.h> struct node { int data1; char data2; struct node* link; }; int main() { 30 40 X
  • 26. 26 struct node ob1; // Node1 // Intialization ob1.link = NULL; ob1.data1 = 10; ob1.data2 = 20; struct node ob2; // Node2 // Initialization ob2.link = NULL; ob2.data1 = 30; ob2.data2 = 40; // Linking ob1 and ob2 ob1.link = &ob2; // Accessing data members of ob2 using ob1 printf("%d", ob1.link->data1); printf("n%d", ob1.link->data2); return 0; } Output: 30 40 UNIONS: A union is a special data type available in C that allows to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple-purpose. Defining a Union: To define a union, you must use the union statement in the same way as you did while defining a structure. The union statement defines a new data type with more than one member for your program. Syntax: union [union tag] { member definition; member definition;
  • 27. 27 ... member definition; } [one or more union variables]; The union tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the union's definition, before the final semicolon, you can specify one or more union variables but it is optional. Example: union Data { int i; float f; char str[20]; } data; Now, a variable of ‘Data’ type can store an integer, a floating-point number, or a string of characters. It means a single variable, i.e., same memory location, can be used to store multiple types of data. The memory occupied by a union will be large enough to hold the largest member of the union. For example, in the above example, Data type will occupy 20 bytes of memory space because this is the maximum space which can be occupied by a character string. The following example displays the total memory size occupied by the above union: Program: #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }; int main( ) { union Data data; printf( "Memory size occupied by data : %dn", sizeof(data)); return 0; } Output: Memory size occupied by data : 20 Accessing Union Members:
  • 28. 28 To access any member of a union, we use the member access operator (.). The member access operator is coded as a period between the union variable name and the union member that we wish to access. You would use the keyword union to define variables of union type. Program: #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }; int main( ) { union Data data; data.i = 10; data.f = 220.5; strcpy( data.str, "C Programming"); printf( "data.i : %dn", data.i); printf( "data.f : %fn", data.f); printf( "data.str : %sn", data.str); return 0; } Output: data.i : 1917853763 data.f : 4122360580327794860452759994368.000000 data.str : C Programming Here, we can see that the values of i and f members of union got corrupted because the final value assigned to the variable has occupied the memory location and this is the reason that the value of str member is getting printed very well. Program: #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; };
  • 29. 29 int main( ) { union Data data; data.i = 10; printf( "data.i : %dn", data.i); data.f = 220.5; printf( "data.f : %fn", data.f); strcpy( data.str, "C Programming"); printf( "data.str : %sn", data.str); return 0; } Output: data.i : 10 data.f : 220.500000 data.str : C Programming Here, all the members are getting printed very well because one member is being used at a tim DATA FILES In C programming, file is a place on your physical disk where information is stored. WHY FILES ARE NEEDED? • When a program is terminated, the entire data is lost. Storing in a file will preserve your data even if the program terminates. • If you have to enter a large number of data, it will take a lot of time to enter them all. However, if you have a file containing all the data, you can easily access the contents of the file using few commands in C. • You can easily move your data from one computer to another without any changes. TYPES OF FILES: When dealing with files, there are two types of files you should know about: • Text files • Binary files Text files: • Text files are the normal .txt files that you can easily create using Notepad or any simple text editors. • When you open those files, you'll see all the contents within the file as plain text. You can easily edit or delete the contents. • They take minimum effort to maintain, are easily readable, and provide least security and takes bigger storage space.
  • 30. 30 Binary files: • Binary files are mostly the .bin files in your computer. • Instead of storing data in plain text, they store it in the binary form (0's and 1's). • They can hold higher amount of data, are not readable easily and provides a better security than text files. C provides a number of functions that helps to perform basic file operations. Following are the functions, Function description fopen() create a new file or open a existing file fclose() closes a file getc() reads a character from a file putc() writes a character to a file fscanf() reads a set of data from a file fprintf() writes a set of data to a file getw() reads a integer from a file putw() writes a integer to a file fseek() set the position to desire point ftell() gives current position in the file rewind() set the position to the begining point FILE OPERATIONS: In C, you can perform four major operations on the file, either text or binary: • Creating a new file • Opening an existing file • Closing a file • Reading from and writing information to a file DECLARATION: When working with files, you need to declare a pointer of type file. This declaration is needed for communication between the file and program. FILE *fptr; OPENING A FILE - FOR CREATION AND EDIT: Opening a file is performed using the library function in the "stdio.h" header file: fopen(). Syntax: fptr=fopen(const char *filename, const char *mode);
  • 31. 31 Example: fopen("E:cprogramnewprogram.txt","w"); fopen("E:cprogramoldprogram.bin","rb"); • Let's suppose the file newprogram.txt doesn't exist in the location E:cprogram. The first function creates a new file named newprogram.txt and opens it for writing as per the mode 'w'.The writing mode allows you to create and edit (overwrite) the contents of the file. • Now let's suppose the second binary file oldprogram.bin exists in the location E:cprogram. The second function opens the existing file for reading in binary mode 'rb'. The reading mode only allows you to read the file, you cannot write into the file. OPENING MODES IN STANDARD I/O: File Mode Meaning of Mode During Inexistence of file R Open for reading. If the file does not exist, fopen() returns NULL. Rb Open for reading in binary mode. If the file does not exist, fopen() returns NULL. W Open for writing. If the file exists, its contents are overwritten. If the file does not exist, it will be created. wb Open for writing in binary mode. If the file exists, its contents are overwritten. If the file does not exist, it will be created. A Open for append. i.e, Data is added to end of file. If the file does not exists, it will be created.
  • 32. 32 File Mode Meaning of Mode During Inexistence of file Ab Open for append in binary mode. i.e, Data is added to end of file. If the file does not exists, it will be created. r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL. rb+ Open for both reading and writing in binary mode. If the file does not exist, fopen() returns NULL. w+ Open for both reading and writing. If the file exists, its contents are overwritten. If the file does not exist, it will be created. wb+ Open for both reading and writing in binary mode. If the file exists, its contents are overwritten. If the file does not exist, it will be created. a+ Open for both reading and appending. If the file does not exists, it will be created. ab+ Open for both reading and appending in binary mode. If the file does not exists, it will be created. CLOSING A FILE: The file (both text and binary) should be closed after reading/writing.Closing a file is performed using library function fclose(). Syntax: fclose(fptr); //fptr is the file pointer associated with file to be closed. READING AND WRITING TO A TEXT FILE: For reading and writing to a text file, we use the functions fprintf() and fscanf().They are just the file versions of printf() and scanf(). The only difference is that, fprint and fscanf expects a pointer to the structure FILE. Program: Write to a text file using fprintf() #include<stdio.h>
  • 33. 33 #include<conio.h> int main() { int num; FILE *fptr; fptr = fopen("C:program.txt","w"); if(fptr == NULL) { printf("Error!"); exit(1); } printf("Enter num: "); scanf("%d",&num); fprintf(fptr,"%d",num); fclose(fptr); return 0; } Output: This program takes a number from user and stores in the file program.txt. After you compile and run this program, you can see a text file program.txt created in C drive of your computer. When you open the file, you can see the integer you entered. Program: Read from a text file using fscanf() #include <stdio.h> #include <conio.h> int main() { int num; FILE *fptr; if ((fptr = fopen("C:program.txt","r")) == NULL){ printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); } fscanf(fptr,"%d", &num); printf("Value of n=%d", num); fclose(fptr); return 0; }
  • 34. 34 Output: This program reads the integer present in the program.txt file and prints it onto the screen. If you succesfully created the file from Example 1, running this program will get you the integer you entered. Other functions like fgetchar(), fputc() etc. can be used in similar way. feof(): Check end-of-file indicator Checks whether the end-of-File indicator associated with stream is set, returning a value different from zero if it is.This indicator is generally set by a previous operation on the stream that attempted to read at or past the end-of-file. Program:to open a file and to print it contents on screen. #include <stdio.h> #include <conio.h> void main() { FILE *fp; char s; clrscr(); fp=fopen("source.txt","r"); if(fp==NULL) { printf("nCAN NOT OPEN FILE"); getch(); exit(); } do { s=getc(fp); printf("%c",s); } while(s!=EOF); fclose(fp); getch(); } Program:to copy files #include<stdio.h> void main() { FILE *fp1,*fp2; char ch; fp1=fopen("source.txt","r"); if(fp1==NULL) { puts("Cannot open this file");
  • 35. 35 exit(1); } fp2=fopen("destination.txt", "w"); if(fp2==NULL) { puts("Not able to open this file"); fclose(fp1); exit(1); } while((ch = fgetc(fp1))!= EOF) { fputc(ch,fp2); } printf("File copied successfully"); fclose(fp2); fclose(fp1); } Program:to merge two files and store the contents in another file #include <stdio.h> void main() { FILE *fp1, *fp2, *fp; char ch; clrscr(); fp1=fopen(sample1.txt,"r"); fp2=fopen(sample2.txt,"r"); if(fp1== NULL||fp2==NULL) { perror("Error"); printf("Press any key to exit...n"); getch(); exit(0); } fp=fopen(mergefile.txt,"w"); if(fp==NULL) { perror("Error "); printf("Press any key to exit...n"); exit(0); } while((ch=fgetc(fp1))!=EOF) { fputc(ch,fp); } while((ch=fgetc(fp2))!=EOF) { fputc(ch,fp);
  • 36. 36 } printf("Two files were merged into %s file successfully.n",mergefile.txt); fclose(fp1); fclose(fp2); fclose(fp); getch(); } Program:to delete a file #include<stdio.h> #include<conio.h> #include<process.h> main() { FILE *fp; char filename[20]; int status; clrscr(); printf("nEnter the file name: "); scanf("%s",filename); fp = fopen(filename, r); if(fp == NULL) { printf("Error: file not found! check the directory!!nn"); exit(0); } fclose(fp); status = remove(file_name); if( status == 0 ) printf("%s file deleted successfully.n",file_name); else { printf("Unable to delete the filen"); perror("Error"); } return 0; } Program:to count the number of characters and number of lines in a file. #include <stdio.h> int main() { FILE *fp; int countl=1; // Line counter int countc=0; // Characters counter char filename[50]; char ch; // To store a character read from file // Get file name from user. The file should be
  • 37. 37 // either in current folder or complete path should be provided printf("Enter file name: ");//Extension is also required scanf("%s", filename); // Open the file fp = fopen(filename, "r"); // Check if file exists if (fp == NULL) { printf("Could not open file %s", filename); exit(1); } // Extract characters from file and store in character ch while((ch=getc(fp))!=EOF) { countc++; if(ch=='n') countl++; } // Close the file fclose(fp); printf("The file %s has %d characters and %d lines ", filename,countc,countl); getch(); return 0; } Output: Enter file name:test.txt The file test.txt has 20 characters and 3 lines