preprocessor directives in c

Before a C program is compiled in a compiler, source code is processed by a program called preprocessor. This process is called preprocessing.


Commands used in preprocessor are called preprocessor directives and they begin with ”#” symbol. Below is the list of preprocessor directives that C language offers.

1 Macro
syntax:
#define 
This macro defines constant value and can be any of the basic data types.

2 Header file inclusion 
syntax:
#include <file_name>
The source code of the file ”file_name” is included in the main program at the specified place

3 Conditional compilation
syntax:
#ifdef, #endif, #if, #else, #ifndef
Set of commands are included or excluded in source program before compilation with respect to the condition

4 Other directives 
syntax:
#undef, #pragma
#undef is used to undefine a defined macro variable.
#Pragma is used to call a function before and after main function in a C program

files in c

Files

In C programming, file is a place on disk where a group of related data is stored.

Why files are needed?

When the program is terminated, the entire data is lost in C programming. If you want to keep large volume of data, it is time consuming to enter the entire data. But, if file is created, these information can be accessed using few commands.

There are large numbers of functions to handle file I/O in C language. In this tutorial, you will learn to handle standard I/O(High level file I/O functions) in C.

High level file I/O functions can be categorized as:

  1. Text file
  2. Binary file

File Operations

  1. Creating a new file
  2. Opening an existing file
  3. Reading from and writing information to a file
  4. Closing a file

Working with file

While working with file, you need to declare a pointer of type file. This declaration is needed for communication between file and program.

FILE *ptr;

Opening a file

Opening a file is performed using library function fopen(). The syntax for opening a file in standard I/O is:

ptr=fopen("fileopen","mode")

For Example:
fopen("E:\\cprogram\program.txt","w"); 
  
/* --------------------------------------------------------- */
 E:\\cprogram\program.txt is the location to create file.   
 "w" represents the mode for writing.
/* --------------------------------------------------------- */

Here, the program.txt file is opened for writing mode.

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.
w Open for writing. 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.
r+ Open for both reading and writing. 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.
a+ Open for both reading and appending. If the file does not exists, it will be created.

 

Closing a File

The file should be closed after reading/writing of a file. Closing a file is performed using library function fclose().

fclose(ptr); //ptr is the file pointer associated with file to be closed.

The Functions fprintf() and fscanf() functions.

The functions fprintf() and fscanf() are the file version of printf() and fscanf(). The only difference while using fprintf()and fscanf() is that, the first argument is a pointer to the structure FILE

Writing to a file


#include <stdio.h>
int main()
{
   int n;
   FILE *fptr;
   fptr=fopen("C:\\program.txt","w");
   if(fptr==NULL){
      printf("Error!");   
      exit(1);             
   }
   printf("Enter n: ");
   scanf("%d",&n);
   fprintf(fptr,"%d",n);   
   fclose(fptr);
   return 0;
}

This program takes the number from user and stores in file. 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 that file, you can see the integer you entered.

Similarly, fscanf() can be used to read data from file.

Reading from file


#include <stdio.h>
int main()
{
   int n;
   FILE *fptr;
   if ((fptr=fopen("C:\\program.txt","r"))==NULL){
       printf("Error! opening file");
       exit(1);         /* Program exits if file pointer returns NULL. */
   }
   fscanf(fptr,"%d",&n);
   printf("Value of n=%d",n); 
   fclose(fptr);   
   return 0;
}

If you have run program above to write in file successfully, you can get the integer back entered in that program using this program.

Other functions like fgetchar()fputc()etc. can be used in similar way.

Binary Files

Depending upon the way file is opened for processing, a file is classified into text file and binary file.

If a large amount of numerical data it to be stored, text mode will be insufficient. In such case binary file is used.

Working of binary files is similar to text files with few differences in opening modes, reading from file and writing to file.

Opening modes of binary files

Opening modes of binary files are rbrb+,wbwb+,ab and ab+. The only difference between opening modes of text and binary files is that, b is appended to indicate that, it is binary file.

Reading and writing of a binary file.

Functions fread() and fwrite() are used for reading from and writing to a file on the disk respectively in case of binary files.

Function fwrite() takes four arguments, address of data to be written in disk, size of data to be written in disk, number of such type of data and pointer to the file where you want to write.

fwrite(address_data,size_data,numbers_data,pointer_to_file);

Function fread() also take 4 arguments similar to fwrite() function as above.

unions in c

Unions

Unions are quite similar to the . Union is also a derived type as structure. Union can be defined in same manner as structures just the keyword used in defining union in union where keyword used in defining structure was struct.

union car{
  char name[50];
  int price;
};

Union variables can be created in similar manner as structure variable.

union car{
  char name[50];
  int price;
}c1, c2, *c3;

OR;

union car{
  char name[50];
  int price;
};
-------Inside Function-----------
union car c1, c2, *c3;

In both cases, union variables c1c2 and union pointer variable c3 of type union caris created.

Accessing members of an union

The member of unions can be accessed in similar manner as that structure. Suppose, we you want to access price for union variable c1 in above example, it can be accessed as c1.price. If you want to access price for union pointer variable c3, it can be accessed as (*c3).price or asc3->price.

Difference between union and structure

Though unions are similar to structure in so many ways, the difference between them is crucial to understand. This can be demonstrated by this example:

#include <stdio.h>
union job {         //defining a union
   char name[32];
   float salary;
   int worker_no;
}u;
struct job1 {
   char name[32];
   float salary;
   int worker_no;
}s;
int main(){
   printf("size of union = %d",sizeof(u));
   printf("\nsize of structure = %d", sizeof(s));
   return 0;
}

Output

size of union = 32
size of structure = 40

There is difference in memory allocation between union and structure as suggested in above example. The amount of memory required to store a structure variables is the sum of memory size of all members.

But, the memory required to store a union variable is the memory required for largest element of an union.

What difference does it make between structure and union?

As you know, all members of structure can be accessed at any time. But, only one member of union can be accessed at a time in case of union and other members will contain garbage value.

#include <stdio.h>
union job {
   char name[32];
   float salary;
   int worker_no;
}u;
int main(){
   printf("Enter name:\n");
   scanf("%s",&u.name);
   printf("Enter salary: \n");
   scanf("%f",&u.salary);
   printf("Displaying\nName :%s\n",u.name);
   printf("Salary: %.1f",u.salary);
   return 0;
}

Output

Enter name 
Hillary
Enter salary
1234.23
Displaying
Name: f%Bary   
Salary: 1234.2

Note: You may get different garbage value of name.

Why this output?

Initially,  Hillary will be stored in u.name and other members of union will contain garbage value. But when user enters value of salary, 1234.23 will be stored inu.salary and other members will contain garbage value. Thus in output, salary is printed accurately but, name displays some random string.

Passing Union To a Function

Union can be passed in similar manner as structures in C programming.

structure & functions in c

Structure and Function

In C, structure can be passed to functions by two methods:

  1. Passing by value (passing actual value as argument)
  2. Passing by reference (passing address of an argument)

Passing structure by value

A structure variable can be passed to the function as an argument as normal variable. If structure is passed by value, change made in structure variable in function definition does not reflect in original structure variable in calling function.

Write a C program to create a structure student, containing name and roll. Ask user the name and roll of a student in main function. Pass this structure to a function and display the information in that function.

#include <stdio.h>
struct student{
    char name[50];
    int roll;
};
void Display(struct student stu);
/* function prototype should be below to the structure declaration otherwise compiler shows error */
int main(){
    struct student s1;
    printf("Enter student's name: ");
    scanf("%s",&s1.name);
    printf("Enter roll number:");
    scanf("%d",&s1.roll);
    Display(s1);   // passing structure variable s1 as argument
    return 0;
}
void Display(struct student stu){
  printf("Output\nName: %s",stu.name);
  printf("\nRoll: %d",stu.roll);
}

Output

Enter student's name: Kevin Amla
Enter roll number: 149
Output
Name: Kevin Amla
Roll: 149

Passing structure by reference

The address location of structure variable is passed to function while passing it by reference. If structure is passed by reference, change made in structure variable in function definition reflects in original structure variable in the calling function.

Write a C program to add two distances(feet-inch system) entered by user. To solve this program, make a structure. Pass two structure variable (containing distance in feet and inch) to add function by reference and display the result in main function without returning it.

#include <stdio.h>
struct distance{
    int feet;
    float inch;
};
void Add(struct distance d1,struct distance d2, struct distance *d3); 
int main()
{
    struct distance dist1, dist2, dist3;
    printf("First distance\n");
    printf("Enter feet: ");
    scanf("%d",&dist1.feet);
    printf("Enter inch: ");
    scanf("%f",&dist1.inch);
    printf("Second distance\n");
    printf("Enter feet: ");
    scanf("%d",&dist2.feet);
    printf("Enter inch: ");
    scanf("%f",&dist2.inch);
    Add(dist1, dist2, &dist3); 

/*passing structure variables dist1 and dist2 by value whereas passing structure variable dist3 by reference */
    printf("\nSum of distances = %d\'-%.1f\"",dist3.feet, dist3.inch);
    return 0;
}
void Add(struct distance d1,struct distance d2, struct distance *d3) 
{
/* Adding distances d1 and d2 and storing it in d3 */
     d3->feet=d1.feet+d2.feet; 
     d3->inch=d1.inch+d2.inch;
     if (d3->inch>=12) {     /* if inch is greater or equal to 12, converting it to feet. */
         d3->inch-=12;
         ++d3->feet;
    }
}

Output

First distance
Enter feet: 12
Enter inch: 6.8
Second distance
Enter feet: 5
Enter inch: 7.5

Sum of distances = 18'-2.3"

Explaination

In this program, structure variables dist1and dist2 are passed by value (because value of dist1 and dist2 does not need to be displayed in main function) and dist3 is passed by reference ,i.e, address of dist3(&dist3) is passed as an argument. Thus, the structure pointer variable d3 points to the address of dist3. If any change is made in d3 variable, effect of it is seed indist3 variable in main function.

structure & pointer in c

Structure and Pointer

Pointers can be accessed along with structures. A pointer variable of structure can be created as below:

struct name {
    member1;
    member2;
    .
    .
};
-------- Inside function -------
struct name *ptr;

Here, the pointer variable of type struct name is created.

Structure’s member through pointer can be used in two ways:

  1. Referencing pointer to another address to access memory
  2. Using dynamic memory allocation

Consider an example to access structure’s member through pointer.

#include <stdio.h>
struct name{
   int a;
   float b;
};
int main(){
    struct name *ptr,p;
    ptr=&p;            /* Referencing pointer to memory address of p */
    printf("Enter integer: ");
    scanf("%d",&(*ptr).a);
    printf("Enter number: ");
    scanf("%f",&(*ptr).b);
    printf("Displaying: ");
    printf("%d%f",(*ptr).a,(*ptr).b);
    return 0;
}

In this example, the pointer variable of type struct name is referenced to the address of p. Then, only the structure member through pointer can can accessed.

Structure pointer member can also be accessed using -> operator.

(*ptr).a is same as ptr->a
(*ptr).b is same as ptr->b

Accessing structure member through pointer using dynamic memory allocation

To access structure member using pointers, memory can be allocated dynamically using malloc() function defined under "stdlib.h" header file.

Syntax to use malloc()

ptr=(cast-type*)malloc(byte-size)

Example to use structure’s member through pointer using malloc() function.

#include <stdio.h>
#include<stdlib.h>
struct name {
   int a;
   float b;
   char c[30];
};
int main(){
   struct name *ptr;
   int i,n;
   printf("Enter n: ");
   scanf("%d",&n);
   ptr=(struct name*)malloc(n*sizeof(struct name));
/* Above statement allocates the memory for n structures with pointer ptr pointing to base address */
   for(i=0;i<n;++i){
       printf("Enter string, integer and floating number  respectively:\n");
       scanf("%s%d%f",&(ptr+i)->c,&(ptr+i)->a,&(ptr+i)->b);
   }
   printf("Displaying Infromation:\n");
   for(i=0;i<n;++i)
       printf("%s\t%d\t%.2f\n",(ptr+i)->c,(ptr+i)->a,(ptr+i)->b);
   return 0;
}

Output

Enter n: 2
Enter string, integer and floating number  respectively:
Programming
2
3.2
Enter string, integer and floating number  respectively:
Structure
6
2.3
Displaying Information
Programming      2      3.20
Structure      6      2.30

structure in c

Structure

Structure is the collection of variables of different types under a single name for better handling. For example: You want to store the information about person about his/her name, citizenship number and salary. You can create these information separately but, better approach will be collection of these information under single name because all these information are related to person.

Structure Definition in C

Keyword struct is used for creating a structure.

Syntax of structure

struct structure_name 
{
    data_type member1;
    data_type member2;
    .
    .
    data_type memeber;
};

We can create the structure for a person as mentioned above as:

struct person
{
    char name[50];
    int cit_no;
    float salary;
};

This declaration above creates the derived data type struct person.

Structure variable declaration

When a structure is defined, it creates a user-defined type but, no storage is allocated. For the above structure of person, variable can be declared as:

struct person
{
    char name[50];
    int cit_no;
    float salary;
};

Inside main function:
struct person p1, p2, p[20];

Another way of creating sturcture variable is:

struct person
{
    char name[50];
    int cit_no;
    float salary;
}p1 ,p2 ,p[20];

In both cases, 2 variables p1p2 and arrayp having 20 elements of type struct person are created.

Accessing members of a structure

There are two types of operators used for accessing members of a structure.

  1. Member operator(.)
  2. Structure pointer operator(->)

Any member of a structure can be accessed as:structure_variable_name.member_name

Suppose, we want to access salary for variable p2. Then, it can be accessed as:

p2.salary

Example of structure

Write a C program to add two distances entered by user. Measurement of distance should be in inch and feet.(Note: 12 inches = 1 foot)


#include <stdio.h>
struct Distance{
    int feet;
    float inch;
}d1,d2,sum;
int main(){
    printf("1st distance\n");
    printf("Enter feet: ");
    scanf("%d",&d1.feet);  /* input of feet for structure variable d1 */
    printf("Enter inch: ");
    scanf("%f",&d1.inch);  /* input of inch for structure variable d1 */
    printf("2nd distance\n");
    printf("Enter feet: ");
    scanf("%d",&d2.feet);  /* input of feet for structure variable d2 */
    printf("Enter inch: ");
    scanf("%f",&d2.inch);  /* input of inch for structure variable d2 */
    sum.feet=d1.feet+d2.feet;
    sum.inch=d1.inch+d2.inch;
    if (sum.inch>12){  //If inch is greater than 12, changing it to feet.
        ++sum.feet;
        sum.inch=sum.inch-12;
    }
    printf("Sum of distances=%d\'-%.1f\"",sum.feet,sum.inch); 
/* printing sum of distance d1 and d2 */
    return 0;
}

Output

1st distance
Enter feet: 12
Enter inch: 7.9
2nd distance
Enter feet: 2
Enter inch: 9.8
Sum of distances= 15'-5.7"

Keyword typedef while using structure

Programmer generally use typedef while using structure in C language. For example:

typedef struct complex{
  int imag;
  float real;
}comp;

Inside main:
comp c1,c2;

Here, typedef keyword is used in creating a type comp(which is of type as struct complex). Then, two structure variables c1and c2 are created by this comp type.

Structures within structures

Structures can be nested within other structures in C programming.

struct complex
{
 int imag_value;
 float real_value;
};
struct number{
   struct complex c1;
   int real;
}n1,n2;

Suppose you want to access imag_valuefor n2 structure variable then, structure member n1.c1.imag_value is used.

string manipulations using library functions in c

String Manipulations Using Library Functions

Strings are often needed to be manipulated by programmer according to the need of a problem. All string manipulation can be done manually by the programmer but, this makes programming complex and large. To solve this, the C supports a large number of string handling functions.

There are numerous functions defined in"string.h" header file. Few commonly used string handling functions are discussed below:

Function Work of Function
strlen() Calculates the length of string
strcpy() Copies a string to another string
strcat() Concatenates(joins) two strings
strcmp() Compares two string
strlwr() Converts string to lowercase
strupr() Converts string to uppercase

Strings handling functions are defined under "string.h" header file, i.e, you have to include the code below to run string handling functions.

#include <string.h>

gets() and puts()

Functions gets() and puts() are two string functions to take string input from user and display string respectively as mentioned in previous chapter.

#include<stdio.h>
int main(){
    char name[30];
    printf("Enter name: ");
    gets(name);     //Function to read string from user.
    printf("Name: ");
    puts(name);    //Function to display string.
    return 0;
}

Though, gets() and puts() function handle string, both these functions are defined in"stdio.h" header file.

string in c

String

In C programming, array of character are called strings. A string is terminated by null character /0. For example:

"c string tutorial"

Here, “c string tutorial” is a string. When, compiler encounters strings, it appends null character at the end of string.

Declaration of strings

Strings are declared in C in similar manner as arrays. Only difference is that, strings are of char type.

char s[5];

Strings can also be declared using pointer.

char *p

Initialization of strings

In C, string can be initialized in different number of ways.

char c[]="abcd";
     OR,
char c[5]="abcd";
     OR,
char c[]={'a','b','c','d','\0'};
     OR;
char c[5]={'a','b','c','d','\0'};

String can also be initialized using pointers

char *c="abcd";

Reading Strings from user.

Reading words from user.

char c[20];
scanf("%s",c);

String variable c can only take a word. It is beacause when white space is encountered, the scanf() function terminates.

Write a C program to illustrate how to read string from terminal.

#include <stdio.h>
int main(){
    char name[20];
    printf("Enter name: ");
    scanf("%s",name);
    printf("Your name is %s.",name);
    return 0;
}

Output

Enter name: Dennis Ritchie
Your name is Dennis.

Here, program will ignore Ritchie because,scanf() function takes only string before the white space.

Reading a line of text

C program to read line of text manually.

#include <stdio.h>
int main(){
    char name[30],ch;
    int i=0;
    printf("Enter name: ");
    while(ch!='\n')    // terminates if user hit enter
    {
        ch=getchar();
        name[i]=ch;
        i++;
    }
    name[i]='\0';       // inserting null character at end
    printf("Name: %s",name);
    return 0;
}

This process to take string is tedious. There are predefined functions gets() andputs in C language to read and display string respectively.

int main(){
    char name[30];
    printf("Enter name: ");
    gets(name);     //Function to read string from user.
    printf("Name: ");
    puts(name);    //Function to display string.
    return 0;
}

Both, the above program has same output below:

Output

Enter name: Tom Hanks
Name: Tom Hanks

Passing Strings to Functions

String can be passed to function in similar manner as arrays as, string is also an array.

#include <stdio.h>
void Display(char ch[]);
int main(){
    char c[50];
    printf("Enter string: ");
    gets(c);             
    Display(c);     // Passing string c to function.    
    return 0;
}
void Display(char ch[]){
    printf("String Output: ");
    puts(ch);
}

Here, string c is passed from main()function to user-defined functionDisplay(). In function declaration, ch[] is the formal argument. 

String handling functions

You can perform different type of string operations manually like: finding length of string, concatenating(joining) two strings etc. But, for programmers ease, many library function are defined under header file <string.h> to handle these commonly used talk in C programming. You will learn more about string hadling function in next chapter.

dynamic memory allocation in c

Dynamic Memory Allocation

The exact size of array is unknown untill the compile time,i.e., time when a compier compiles code written in a programming language into a executable form. The size of array you have declared initially can be sometimes insufficient and sometimes more than required. Dynamic memory allocation allows a program to obtain more memory space, while running or to release space when no space is required.

Although, C language inherently does not has any technique to allocated memory dynamically, there are 4 library functions under "stdlib.h" for dynamic memory allocation.

Function Use of Function
malloc() Allocates requested size of bytes and returns a pointer first byte of allocated space
calloc() Allocates space for an array elements, initializes to zero and then returns a pointer to memory
free() dellocate 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 voidwhich can be casted into pointer of any form.

Syntax of malloc()

ptr=(cast-type*)malloc(byte-size)

Here, ptr is pointer of cast-type. Themalloc() 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.

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.

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 of calloc()

ptr=(cast-type*)calloc(n,element-size);

This statement will allocate contiguous space in memory for an array of nelements. For 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.

free()

Dynamically allocated memory with either calloc() or malloc() does not get return on its own. The programmer must use free() explicitly to release space.

syntax of free()

free(ptr);

This statement cause the space in memory pointer by ptr to be deallocated.

Examples of calloc() and malloc()

Write a C program to find sum of n elements entered by user. To perform this program, allocate memory dynamically using malloc() function.


#include <stdio.h>
#include <stdlib.h>
int main(){
    int n,i,*ptr,sum=0;
    printf("Enter number of elements: ");
    scanf("%d",&n);
    ptr=(int*)malloc(n*sizeof(int));  //memory allocated using malloc
    if(ptr==NULL)                     
    {
        printf("Error! memory not allocated.");
        exit(0);
    }
    printf("Enter elements of array: ");
    for(i=0;i<n;++i)
    {
        scanf("%d",ptr+i);
        sum+=*(ptr+i);
    }
    printf("Sum=%d",sum);
    free(ptr);
    return 0;
}

Write a C program to find sum of n elements entered by user. To perform this program, allocate memory dynamically using calloc() function.

#include <stdio.h>
#include <stdlib.h>
int main(){
    int n,i,*ptr,sum=0;
    printf("Enter number of elements: ");
    scanf("%d",&n);
    ptr=(int*)calloc(n,sizeof(int));
    if(ptr==NULL)
    {
        printf("Error! memory not allocated.");
        exit(0);
    }
    printf("Enter elements of array: ");
    for(i=0;i<n;++i)
    {
        scanf("%d",ptr+i);
        sum+=*(ptr+i);
    }
    printf("Sum=%d",sum);
    free(ptr);
    return 0;
}

realloc()

If the previously allocated memory is insufficient or more than sufficient. Then, you can change memory size previously allocated using realloc().

Syntax of realloc()

ptr=realloc(ptr,newsize);

Here, ptr is reallocated with size of newsize.

#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("%u\t",ptr+i);
    printf("\nEnter new size of array: ");
    scanf("%d",&n2);
    ptr=realloc(ptr,n2);
    for(i=0;i<n2;++i)
         printf("%u\t",ptr+i);
    return 0;
}

pointers & functions in c

Pointers and Functions 

Call by Reference

When, argument is passed using pointer, address of the memory location is passed instead of value.

Example of Pointer And Functions

Program to swap two number using call by reference.

 /* C Program to swap two numbers using pointers and function. */
#include <stdio.h>
void swap(int *a,int *b);
int main(){
  int num1=5,num2=10;
  swap(&num1,&num2);  /* address of num1 and num2 is passed to swap function */
  printf("Number1 = %d\n",num1);
  printf("Number2 = %d",num2);
  return 0;
}
void swap(int *a,int *b){ /* pointer a and b points to address of num1 and num2 respectively */
  int temp;
  temp=*a;
  *a=*b;
  *b=temp;
}

Output

Number1 = 10
Number2 = 5

Explanation

The address of memory location num1and num2 are passed to function and the pointers *a and *b accept those values. So, the pointer a and b points to address of num1 and num2 respectively. When, the value of pointer are changed, the value in memory location also changed correspondingly. Hence, change made to*a and *b was reflected in num1 and num2in main function.

This technique is known as call by reference in C programming.