Saturday, August 27, 2011

How to open website using C

You can easily open your website using C. You can pass your website URL as an argument. When you run the code, this will open the URL in the browser. The code is very simple. You have to include <stdlib.h> or <windows.h> to use it.

#include<windows.h>

int main()
{
    system("explorer http://www.programming-technique.blogspot.com");
    return 0;
}

How to change the text color of console using C

The following code changes the text color of console to the color defined by color value supplied. You must include <windows.h> to use this function. It works on windows only.

#include <stdio.h>
#include <windows.h>
#include <conio.h>
void SetColor(int ForgC)
{
     WORD wColor;
     HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
     CONSOLE_SCREEN_BUFFER_INFO csbi;
     if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
     {
          wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
          SetConsoleTextAttribute(hStdOut, wColor);
     }
     return;
}
int main(){
  int fore;
  printf("Enter text color value: ");
  scanf("%d",&fore);
  SetColor(fore);
  printf("Your color will be like this");
  getch();
  return 0;
}

Output


text_color

How to change Background and Foreground color of Console in C

<windows.h> provides various functions to change the properties of windows like changing color, resizing windows, changing cursor position etc. The source code for changing the background and foreground color of console is given below. You can pass different color values to the function to get different color in background and foreground.

#include <stdio.h>
#include <windows.h>
#include <conio.h>
void SetColorAndBackground(int ForgC, int BackC)
{
     WORD wColor = ((BackC & 0x0F) << 4) + (ForgC & 0x0F);;
     SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), wColor);
     return;
}
int main(){
  int fore, back;
  printf("Enter foreground and background color values: ");
  scanf("%d%d",&fore, &back);
  SetColorAndBackground(fore,back);
  printf("Your color will be like this");
  getch();
  return 0;
}

Output


bfcolor

gotoxy() function in Code::blocks(gcc compiler) using C

In Turbo C/C++ and Borland C++ compiler, gotoxy() is build in function. You need not have to write its function definition. All you have to do is call the function with arguments as x and y coordinate. But in modern C compiler like gcc and IDE Code::Blocks, gotoxy() is not  build-in function, you have to define it before use them. The following code is the function definition for gotoxy(). Remember: This function only works on windows, because the function definition includes functions of header file “windows.h”. So to use gotoxy() you must include “windows.h”.

COORD coordinate = {0,0}; //initialization

void gotoxy(int x, int y){ //function definition
   coordinate.X = x; coordinate.Y =  y;
   SetConsoleCursorPostion(GetStdHandle(STD_OUTPUT_HANDLE),coordinate);
}

NOTE: coordinate (0,0) is left-top corner of your window.

Returning Two Dimensional Array from a Function in C

Many authors do not include topics about returning an array from a function in their books or articles. It is because, in most of the cases, there is no need of array to be returned from a function. Since, on passing the array by its name, the address of its first member is passed and any changes made on its formal arguments reflects on actual arguments.

But sometimes, there may arise the situation, where an array has to be returned from a function, for example, multiplying two matrices and assigning the result to another matrix. This can be done by creating a two-dimensional array inside a function, allocating a memory and returning that array. The important thing is you need to FREE the matrix that was allocated.

The source code of returning a two-dimensional array with reference to matrix addition is given here.
#include <stdio.h>
#include <stdlib.h>

int **matrix_sum(int matrix1[][3], int matrix2[][3]){
    int i, j;
    int **matrix3;
    matrix3 = malloc(sizeof(int*) * 3);
    
    for(i = 0; i < 3; i++) {
        matrix3[i] = malloc(sizeof(int*) * 3);
    }

    for(i = 0; i < 3; i++){
        for(j = 0; j < 3; j++){
            matrix3[i][j] = matrix1[i][j] + matrix2[i][j];
        }
    }
    return matrix3;
}



int main(){
    int x[3][3], y[3][3];
    int **a;
    int i,j;


    printf("Enter the matrix1: \n");
    for(i = 0; i < 3; i++){
        for(j = 0; j < 3; j++){
            scanf("%d",&x[i][j]);
        }
    }


    printf("Enter the matrix2: \n");
    for(i = 0; i < 3; i++){
        for(j = 0; j < 3; j++){
            scanf("%d",&y[i][j]);
        }
    }


    a = matrix_sum(x,y); //asigning
    printf("The sum of the matrix is: \n");
    for(i = 0; i < 3; i++){
        for(j = 0; j < 3; j++){
            printf("%d",a[i][j]);
            printf("\t");
        }
        printf("\n");
    }

    //free the memory
    for(i = 0; i < 3; i++) {
        free(a[i]);
    }
    free(a);
    return 0;
}

Or you can use a structure that has a two-dimensional array as a member. Create an instance of structure inside the function and return it.  The code for this approach is given below.
#include <stdio.h>
#include <stdlib.h>

typedef struct {
 int m[3][3];
} arr2d;

arr2d matrix_sum(int matrix1[][3], int matrix2[][3]){
    int i, j;
    arr2d result;

    for(i = 0; i < 3; i++){
        for(j = 0; j < 3; j++){
            result.m[i][j] = matrix1[i][j] + matrix2[i][j];
        }
    }
    return result;
}

int main(){
    int x[3][3], y[3][3];
    arr2d result;
    int i,j;

    printf("Enter the matrix1: \n");
    for(i = 0; i < 3; i++){
        for(j = 0; j < 3; j++){
            scanf("%d",&x[i][j]);
        }
    }

    printf("Enter the matrix2: \n");
    for(i = 0; i < 3; i++){
        for(j = 0; j < 3; j++){
            scanf("%d",&y[i][j]);
        }
    }

    result = matrix_sum(x,y);
    printf("The sum of the matrix is: \n");
    for(i = 0; i < 3; i++){
        for(j = 0; j < 3; j++){
            printf("%d",result.m[i][j]);
            printf("\t");
        }
        printf("\n");
    }

    return 0;
}

Mini project Employee record system using C

The employee record system is very simple and for very beginner mini project. It is based one the menu-driven program for elementary database management. It employs all the basic technique of file handling in C. It consists of following features
  • Writing the data in binary file
  • Reading the data from binary file
  • Modify the record
  • Delete the record
This project is a learning milestone for a beginner who wants to step into the database management project in C. The code is also available on GitHub.

Here are List of Mini projects in C

Source Code
/**
*  A menu-driven program for elementary database management
*  @author: Bibek Subedi
*  @language: C
*  This program uses file handling in Binary mode
*/
 
/// List of library functions
#include <stdio.h> ///for input output functions like printf, scanf
#include <stdlib.h>
#include <string.h>  ///string operations

// Copied from 
// https://stackoverflow.com/questions/35103745/read-a-string-as-an-input-using-scanf
void flush()
{
    int c;
    while ((c = getchar()) != '\n' && c != EOF);
}

/** Main function started */
 
int main(){
    FILE *fp, *ft; /// file pointers
    char another, choice;
 
    /** structure that represent a employee */
    struct emp{
        char name[40]; ///name of employee
        int age; /// age of employee
        float bs; /// basic salary of employee
    };
 
    struct emp e; /// structure variable creation
 
    char empname[40]; /// string to store name of the employee
 
    long int recsize; /// size of each record of employee
 
    /** open the file in binary read and write mode
    * if the file EMP.DAT already exists then it open that file in read write mode
    * if the file doesn't exit it simply create a new copy
    */
    fp = fopen("EMP.DAT","rb+");
    if(fp == NULL){
        fp = fopen("EMP.DAT","wb+");
        if(fp == NULL){
            printf("Connot open file");
            exit(1);
        }
    }
 
    /// sizeo of each record i.e. size of structure variable e
    recsize = sizeof(e);
 
    /// infinite loop continues untile the break statement encounter
    while(1){
        printf("1. Add Record\n"); /// option for add record
        printf("2. List Records\n"); /// option for showing existing record
        printf("3. Modify Records\n"); /// option for editing record
        printf("4. Delete Records\n"); /// option for deleting record
        printf("5. Exit\n"); /// exit from the program
        printf("Your Choice: "); /// enter the choice 1, 2, 3, 4, 5
        fflush(stdin); /// flush the input buffer
        scanf("\n%c", &choice); /// get the input from keyboard
        switch(choice){
            case '1':  /// if user press 1
                fseek(fp,0,SEEK_END); /// search the file and move cursor to end of the file
                                        /// here 0 indicates moving 0 distance from the end of the file
                another = 'y';
                while(another == 'y'){ /// if user want to add another record
                    flush();
                    printf("\nEnter name: ");
                    fgets(e.name, 40, stdin);
                    printf("\nEnter age: ");
                    scanf("%d", &e.age);
                    printf("\nEnter basic salary: ");
                    scanf("%f", &e.bs);
 
                    fwrite(&e,recsize,1,fp); /// write the record in the file
 
                    printf("\nAdd another record(y/n) ");
                    fflush(stdin);
                    scanf("\n%c", &another);
                }
                break;
            case '2':
                rewind(fp); ///this moves file cursor to start of the file
                while(fread(&e,recsize,1,fp)==1){ /// read the file and fetch the record one record per fetch
                    printf("\n%s %d %.2f\n",e.name,e.age,e.bs); /// print the name, age and basic salary
                }
                break;
 
            case '3':  /// if user press 3 then do editing existing record
                another = 'y';
                while(another == 'y'){
                    printf("Enter the employee name to modify: ");
                    scanf("%s", empname);
                    rewind(fp);
                    while(fread(&e,recsize,1,fp)==1){ /// fetch all record from file
                        if(strcmp(e.name,empname) == 0){ ///if entered name matches with that in file
                            printf("\nEnter new name,age and bs: ");
                            scanf("%s%d%f",e.name,&e.age,&e.bs);
                            fseek(fp,-recsize,SEEK_CUR); /// move the cursor 1 step back from current position
                            fwrite(&e,recsize,1,fp); /// override the record
                            break;
                        }
                    }
                    printf("\nModify another record(y/n)");
                    fflush(stdin);
                    scanf("\n%c", &another);
                }
                break;
            case '4':
                another = 'y';
                while(another == 'y'){
                    flush();
                    printf("\nEnter name of employee to delete: ");
                    fgets(empname,40, stdin);
                    ft = fopen("Temp.dat","wb");  /// create a intermediate file for temporary storage
                    rewind(fp); /// move record to starting of file
                    while(fread(&e,recsize,1,fp) == 1){ /// read all records from file
                        if(strcmp(e.name,empname) != 0){ /// if the entered record match
                            fwrite(&e,recsize,1,ft); /// move all records except the one that is to be deleted to temp file
                        }
                    }
                    fclose(fp);
                    fclose(ft);
                    remove("EMP.DAT"); /// remove the orginal file
                    rename("Temp.dat","EMP.DAT"); /// rename the temp file to original file name
                    fp = fopen("EMP.DAT", "rb+");
                    printf("Delete another record(y/n)");
                    fflush(stdin);
                    scanf("\n%c", &another);
                }
                break;
            case '5':
                fclose(fp);  /// close the file
                exit(0); /// exit from the program
        }
    }
    return 0;
}

Binary Vs Text File in C

From the programming angle, there are three main areas where text and binary mode files are different. These are:
  • Handling of newlines
  • Representation of end of file
  • Storage of numbers
Let us explore these three differences:
In text mode, a newline character is converted into the carriage return-linefeed combination before being written to the disk. Likewise, the carriage return-linefeed combination on the disk is converted back into a newline when the file is read by a C program. However, if a file is opened in binary mode, as opposed to text mode, these conversions will not take place.
The second difference between text and binary modes is in the way the end-of-file is detected. In text mode, a special character, whose ASCII value is 26, is inserted after the last character in the file to mark the end of a file. If this character is detected at any point in the file, the read function would return the EOF signal to the program. As against this, there is no such special character present in the binary mode files to mark the end of a file. The binary mode files keep track of the end of file from the number of character present in the directory entry of the file.
The last difference is storage of numbers. In the text file, the text and characters are stored one character per byte, as we expect. But numbers are stored as strings of characters. Thus, 65112, even though it occupies 4 bytes in memory when transferred to the disk using fprintf(), would occupy 5 bytes, one byte per character. Here if a large amount of data is to be stored in a disk file, using text mode may turn out to be insufficient. The solution is to open the file in binary mode and use those functions (fread() and fwrite()) ) which store the numbers in binary format. It means each number would occupy a same number of bytes on disks as it occupies in memory. 

Writing into and reading from a binary file in C

In previous example, you learn how to write and read a text file in C. If the number of fields in the structure increase, writing structures using fprintf(), or reading them using fscanf(), becomes quite clumsy. The more efficient way of writing records(structures) can be achieved by the use of two functions fread() and fwrite(). The fwrite() functions writes whole structures at a time and fread() function read all the fields at a time.

Writing into the binary file

The following code segment illustrates how to write data into file in binary format.

struct emp{
   char name[20];
   int age;
   float bs;
};
struct emp e;
fp = fopen("EMP.DAT","wb");
if(fp == NULL){
   puts("Cannot open file");
}
printf("Enter name, age and basic salary");
scanf("%s%d%f",e.name,&e.age,&e.bs);
fwrite(&e,sizeof(e),1,fp);
fclose(fp);
}

Reading from the binary file


The following code segment illustrates how to read data from file in binary format.

fp = fopen("EMP.DAT","rb");
while(fread(&e,sizeof(e),1,fp)==1){
   printf("%s %d %f\n",e.name,e.age,e.bs);
}
fclose(fp);

Tuesday, August 23, 2011

Writing into and reading from a text file in C

We use fprintf() and fscanf() functions to write into the file and read from file respectively. fprintf()  writes the data to the text file and fscanf() reads the data from from file. The following example illustrates the concept….

Writing into the text file

#include<stdio.h>
#include<stdlib.h>
int main(){
    FILE *fp;
    struct emp{
        char name[40];
        int age;
        float bs;
    };
    struct emp e;
    //opening file in writing mode
    //this code creates a file named employ.dat if
    //it is not created or writes on the file if it
    //is already created.
    fp = fopen("employ.dat","w");
    if(fp == NULL){ //if file is not opened
        puts("Cannot open file");
        exit(1);
    }
    printf("\nEnter name, age and basic salary: ");
    scanf("%s %d %f", e.name, &e.age, &e.bs);
    //writes name age and basic salary to the file
    fprintf(fp, "%s %d %f\n", e.name, e.age, e.bs);
    fclose(fp); //close the file
    return 0;
}

Reading from the file


 

#include<stdio.h>
#include<stdlib.h>
int main(){
    FILE *fp;
    struct emp{
        char name[40];
        int age;
        float bs;
    };
    struct emp e;
    //opening file in writing mode
    //this code try to open the employ.dat
    //if it is already existed and returns null
    //to fp it is not existed
    fp = fopen("employ.dat","r");
    if(fp == NULL){ //if file is not opened
        puts("Cannot open file");
        exit(1);
    }
    printf("\nThe name, age and basic salary are: ");
    //search the file until end of file encountered
    while(fscanf(fp, "%s %d %f\n", e.name, &e.age, &e.bs)!=EOF){
        printf("%s %d %f\n",e.name,e.age,e.bs);
    }
    fclose(fp); //close the file
    return 0;
}

C Programming: File Handling

The console function like printf() and scanf() have been used for input/output .This scheme is adequate if the volume of data involved in not so large or it is not necessary to store the information for further use. However, many applications may require a large amount of data to be read, processed, and also saved for later use. Such information is stored on the auxiliary memory device in the form of a data file.And a file is a collection of bytes that is given a name. In most computer systems, files are used as a unit of storage primarily on floppy-disk or fixed-disk data storage system (or they can be CDs or other storage devices). Thus data files allow us to store information permanently, and to access and alter that information whenever necessary. The file handling function available in the standard library in order to implement I/O model is classified as follows:
a) File access
b) Operation input/output
c) Formatted input/output
d) Character input/output
e) Direct input/output
f) File positioning
g) Error handling

Difference between Arrays and Structures in C

Both the arrays and structures are classified as structured data types as they provide a mechanism that enables us to access and manipulate data in a relatively easy manner. But they differ in a number of ways listed in the table below:

Arrays
Structures
1. An array is a collection of related data elements of the same type. 1. Structure can have elements of different  types
2. An array is a derived data type 2. A structure is a programmer-defined data type
3. Any array behaves like a built-in data types. All we have to do is to declare an array variable and use it. 3. But in the case of structure, first, we have to design and declare a data structure before the variable of that type are declared and used.
4. Array allocates static memory and uses index/subscript for accessing elements of the array.4. Structures allocate dynamic memory and uses (.) operator for accessing the member of a structure.
5. An array is a pointer to the first element of it5. Structure is not a pointer
6. Element access takes relatively less time.6. Property access takes relatively large time.

Let me explain each point one by one with an example of each.

First, an array is a collection of related data elements of the same type. You can't have an array of different data types in C (you can do this in Python). The following program throws an error in C

int array[5] = {1, 2, "string", 4, 5};




However, in Structure, you can have elements of different data types. The following program compiles without an error.

struct Person {
char name[10];
int age;
float height;
};

Second, an array is a derived data type. Derived data type means they are derived from fundamental data types. An array can be a collection of int, char, float, double, ... but it is not a data type in itself. It adds the additional functionality to the existing data types. But, a structure is a user-defined data type. A user has all the right to create a data type to satisfy his needs. For example, the user may need a data type to represent a book.  Can a book be represented by fundamental data type? Can a book be represented by an int? or Float? or String? the integer can be used represent the total number of pages,  similarly, the float can be used to represent the price of the book and string can be used to represent the title and author of the book. But one integer alone can't represent a whole book but it requires a combination of different fundamental data types.

struct Book {
char title[50];
char author[50];
float price;
int pages;
};

A structure is, therefore, a new data type. Just like int, char or float, structure creates a new data type.
This means we can have an array of structures just like we can have an array of integers. The following code snippet creates an array of structure Book.

struct Book books[2];

'books' is an array of data type 'Book' which can contain two books.

Here are other related articles related to Array

  1. Difference between Array and Pointer in C/C++
  2. Maximum and Minimum elements of an Array



Adding two complex numbers using Structure in C

Simple algebraic addition does not work in the case of Complex Number. Because they have two parts, Real and Imaginary. To add two complex numbers, a real part of one number must be added with a real part of other and imaginary part one must be added with an imaginary part of other. The concept of complex number can be viewed as a structure having two members real and imaginary. So to add two complex numbers we use structure addition. If complex1 and complex2 be two structure variables and complex3 be their sum then
complex3.real = complex1.real + complex2.real;
complex3.imag = complex1.imag + complex2.imag;
In this way, we can add two complex numbers. The source code and output of the program is given here…
Source Code:

#include<stdio.h>
struct comp{
    float real;
    float imag;
};
struct comp comp1,comp2;
struct comp sum_complex(struct comp complex1,struct comp complex2){
    struct comp temp;
    temp.real = complex1.real + complex2.real;
    temp.imag = complex1.imag + complex2.imag;
    return temp;
}
int main(){
    struct comp result;
    printf("Enter Complex Number 1: ");
    scanf("%f%f",&comp1.real, &comp1.imag);
    printf("Enter Complex Number 2: ");
    scanf("%f%f",&comp2.real,&comp2.imag);
    result = sum_complex(comp1,comp2);
    printf("The sum is %.2f + i%.2f\n\n", result.real,result.imag);
    return 0;
}

Output
complex

Electricity Billing System using Structures in C

This example illustrates the concept of structures discussed in previous post. Here structure variable bill is declared which has structure template Bill and members firstName, lastName, Address, previousUnit and presentUnit. The structure represents the information of a customer and the program calculates the cost by checking previous and present unit. After you understand the code you will have the knowledge of following things:

  1. Defining Structure
  2. Declaring Structure variable
  3. Accessing members of structure
  4. Passing structure in function
  5. Returning structure from function

The source code and output is given here…

Source Code

//generating electricity bill using structure in C
#include<stdio.h>
/** This block defines the structure Bill having
    fields for first name, last name, address,
    previous unit and present unit. The structure
    must be defined before main function */
struct Bill{
    char firstName[10];
    char lastName[10];
    char Address[20];
    float previousUnit;
    float presentUnit;
};
/** This is the function definition that
    calculates the cost. Here structure is passed
    as an argument */
float generateBill(struct Bill temp){
    float diff;
    diff = temp.presentUnit - temp.previousUnit;
    if(diff > 20){
        return diff*4.75;
    }else{
        return 20*4.75+(diff-20)*7.75;
    }
}
int main(){
    struct Bill bill; /*Declaration of structure variable*/
    printf("Fill up the following: \n");
    printf("First Name: ");
    gets(bill.firstName); //accessing member
    printf("Last Name: ");
    gets(bill.lastName);
    printf("Address: ");
    gets(bill.Address);
    printf("Previous Unit: ");
    scanf("%f",&bill.previousUnit);
    printf("Present Unit: ");
    scanf("%f",&bill.presentUnit);
    printf("\a\n\n***********Electricity Bill***************\n\n\a");
    printf("Name: %s %s",bill.firstName,bill.lastName);
    printf("\nAddress: %s",bill.Address);
    printf("\nPrevious Unit: %.3f       Current Unit: %.3f",bill.previousUnit,bill.presentUnit);
    printf("\nCost: %.3f\n\n", generateBill(bill));
    return 0;
}

Output


struct

C Programming: Structures

We know that array is a collection of data that represent same data type. We cannot make an array that has data with different types using a single name. Fortunately, C supports a constructed data type called structures a mechanism for packing data of different types. A structure is a convenient tool for handling a group of logically related data items. For example, it can be used to represent a set of attributes, such as student_name, roll_number and marks. The concept of a structure is analogous to that of a ‘record’ in many other languages.
Defining a structure
Unlike arrays, structures must be defined first for their format they may be used later to declare structure variable. the structure definition is the template of structure variable. The general format of a structure definition is
struct tag_name
{
   data_type    member1;
   data_type    member 2;
   - - - - -    - - - - 
};
Declaring structure variable
After defining a structure format you can declare variables of that type. 
A structure variable declaration is similar to the declaration of variable of any other types.
 It includes the following elements:

  • The keyword struct
  • The structure tag name
  • List of variable names separated by commas.
  • A terminating semicolon
The general syntax is 
struct tag_name variable1, variable2, variable3,...,variableN;


Example
1: struct student{
2:    char name[10];
3:    int roll_no;
4:    float marks;
5: };
6: 
7: struct student student1;

In this example line numbers, 1-5 is structure definition. A structure is defined as tag_name student having members name, roll_no and marks. This is only templated for structure variable. Remember members themselves are not variables. They do not occupy any memory until they are associated with the structure variables such as student1 in above example. Till line 7 no variable is created and structure definition cannot do anything without a variable. Line 7 declares a structure variable student1 which has fields name, roll_no and marks. If you declare another variable like student2 then it also includes those fields(members). 

Accessing structure members

We can access and assign values to the members of a structure in a number of ways. As mentioned earlier, the members themselves are not variables. They should be linked to the structure variables in order to make them meaningful members. The link between a member and a variable is established using the member operator ‘.’which is also known as ‘dot operator’ or ‘period operator’. For example, student1.marks is the variable representing the marks of student1 and can be treated like any other ordinary variables.

Wednesday, August 17, 2011

Sorting strings alphabetically using C

Source Code

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void reorder(int n, char *x[]);
int main(){
    int i , no_string;
    char *x[10];
    printf("Enter the no of strings: ");
    scanf("%d",&no_string);
    printf("Enter the strings: \n");
    for(i = 0; i < no_string; i++){
        x[i] = (char*) malloc (12*sizeof(char));
        printf("string %d: ",i+1);
        scanf("%s", x[i]);
    }
    printf("The sorted strings are: ");
    reorder(i,x);
    for(i = 0; i < no_string; i++){
        printf("\nstring %d: %s", i+1, x[i]);
    }
    return 0;
}
void reorder(int n, char *x[]){
    char *temp;
    int i,item;
    for(item = 0; item < n-1; ++item){
        for(i = item+1; i < n; ++i){
            if(strcmp(x[item],x[i]) > 0){
                temp = x[item];
                x[item] = x[i];
                x[i] = temp;
            }
        }
    }
    return;
}

Output



string_sort

C Programming: Dynamic Memory Allocation (DMA)

C language requires the number of elements in an array to be specified at compile time. But we may not be able to do so always. Our initial judgment of size, if it is wrong, may cause failure of the program or wastage of memory space. Many language permit a programmer to specify an array’s size at run time. Such languages have the ability to calculate and assign, during execution, the memory space required by the variables in a program. The process of allocating memory at run time is known as dynamic memory allocation.

Allocating a Block of Memory

A block of memory may be allocated using the function malloc. The malloc function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. General syntax is

ptr = (cast_type*) malloc (byte-size);

ptr is a pointer of type cast_type. The malloc returns a pointer (of cast_type) to an area of memory with size byte_size. Example:

x = (int*) malloc (100*sizeof(int));

On successful execution of this statement, a memory space equivalent to “100 times the size of and int” bytes is reserved and the address of the first byte of the memory allocated is assigned to the pointer x of type of int.


Releasing the used space


When we no longer need the data we stored in a block of memory, and we do not intend to use that block for storing any other information, we may release that block of memory for future use, using the free function:

free(ptr);

Tuesday, August 16, 2011

String operations (length, compare, copy, concatenate) without including string.h using C

In C, string.h includes various build in functions for string operations. The main operations are
1. Length of the string (strlen)
The syntax of strlen is :
strlen(string);
It calculates the length of the string and returns its length. For example:

#include<string.h>
string = "Mumbai";
printf("Length = %d",strlen(string));

The above code displays 5 because Mumbai consists of 5 characters. Note: it does not count null character.

2. Joining two strings (strcat)

The syntax of strcat is
strcat(string1,string2);
Now it removes the null character from string1 and joins the first character of string2 at that position. Now, string1 consists of both string1 and string2 in joined form. Example:

#include<string.h>=
char string1[] = "Anti";
char string2[] = "Particle";
strcat(string1,string2);=
printf("%s",string1); //display AntiParticle

3. Comparing two strings(strcmp)

The syntax of strcmp is
strcmp(string1,string2);
It returns 0 if string1 is same as string2 and returns 1 if they are not same. Example:

#include<string.h>
char string1 = "Nepal";
char string2 = "Srilanka";
if(strcmp(string1,string2)==0){
printf("They are equal");
}else{
printf("They are not equal"); //this is executed
} 

4. Copying one string to another (strcpy)

The syntax of strcpy is

strcpy(destination_string, source_string);

It copies the content of source_string to destination_string. Example:

#include<string.h>
char source[] = "Hello";
char destination[10]; //uninitialized
strcpy(destination,source);
printf("%s",destination); //prints Hello 
These are some of the functions in string.h for string operation. To use these functions you must include header file <string.h>. But we can make our own functions to perform above task without including string,h. Here is the complete source code that has own functions find_length (like strlen) to find the length, join_strings( like strcat) for joining strings, compare_strings(like strcmp) for comparing two strings and copy_string(like strcpy) to copy one string from another. Observer carefully the code, if you are a beginner, you will learn a lot of things about string operation.

Source Code

C Programming: Strings

iA string is a sequence of characters( Array of character)  that is treated as a single data item. Any group of characters (except double quote sign) defined between double quotation marks is a string constant. Example:

“All is Well”

If you want to include a double quote in the string to be printed, then you may use it with a back slash as shown below:

“\”All is Well, \” said Amir Khan.”

Declaring String Variables

C does not support strings as a data type as C++, JAVA etc. However, it allows us to represent strings as character arrays. In C, therefore, a string variable is any valid C variable name and is always declared as an array of characters. The general syntax of declaration of string is:

char string_name [ size];

The size determines the number of characters in the string_name. Example: char city[20]; When the compiler assigns a character string to a character array, it automatically supplies a null character(‘\0’) at the end of the string. Therefore, the size should be equal to the maximum number of characters in the string plus one.


Initializing string variable 


C permits a character array to be initialized in either of the following two forms:

  1: char city[10] = "Kathmandu";
  2: char city[10] = {'K','a','t','h','m','a','n','d','u','\0'};

The reason that city had to be 10 elements long is that the string Kathmandu contains 9 characters and one element space is provided for the null terminator.


Reading String from user


The familiar input function scanf can be used with %s format specification to read in a string of characters. Example:

char address[10];
scanf("%s",address);
 

Note that there is no amp percent(&) before address , it is because address itself represents the first address of string. The problem with scanf with %s  is that it terminates its input on the first white space it finds. For example if I enter NEW YORK, then it only takes NEW as input and neglects YORK. To avoid this you can write following code to read input

  1: char address[10];
  2: scanf("%[^\n]", address];
  3: gets(address)

You can either use scanf with %[^\n] as format specification or use gets(string_name).

Difference between array and pointer in C/C++

The difference between pointer and array in C/C++ is tabulated below. 


Pointer Array
1. A pointer is a place in memory that keeps the address of another place inside
1. An array is a single, pre-allocated chunk of contiguous elements (all of the same type), fixed in size and location.
2. Pointer can’t be initialized at definition.

2. Array can be initialized at definition. Example
int num[] = { 2, 4, 5}
3. Pointer is dynamic in nature. The memory allocation can be resized or freed later.
3. They are static in nature. Once the memory is allocated, it cannot be resized or freed dynamically.
4. The assembly code of Pointer is different than Array
4. The assembly code of Array is different than Pointer.

C Programming: Advantages and Drawbacks of Pointers

Advantages
Pointers are more efficient in handling arrays and data tables. They can be used to return multiple values from a function via function arguments. Pointers permit references to functions and thereby facilitating passing of functions as arguments to other functions. The use of po0inter arrays to character strings results in saving of data storage space in memory. pointers allow C to support dynamic memory management. Pointers provide an efficient tool for manipulating dynamic data structures such as structures, linked lists, queues, stacks, and trees. Pointers reduce length and complexity of programs. They increase the execution speed and thus reduce the program execution time.
Disadvantages
Pointers have tremendous power but the power can swing both sides good and evil. Pointer, if used incorrectly, leads to very difficult to unearth bugs which will most probably make you go wild. Pointers are itself are not any trouble but the value they are storing can be. If it contains an incorrect value it can lead to disasters of massive magnitude when used.
When you use this incorrect pointer to read a memory location, you may be reading an incorrect garbage value which if unluckily accepted by your program as assumed correct value nothing can help you. Consider a scenario in banking in which any customers real account value is switched with this garbage value, he can become a millionaire or beggar in a second, or think that in a rocket launching software you use this incorrect value as launching angle and crashing the billion dollar masterpiece. These scenarios are just my imagination running wild but you cannot ignore the fact that they are the possibility.
Now when you use this incorrect pointer to write a memory location you may be writing an unknown memory location. If you have a large memory in the system maybe you are using an unassigned memory but if that memory by any luck is a memory used by O.S. or Hardware and you are modifying it you maybe corrupting your Operating System software or damaging your hardware and their drivers. Also, it is a possibility that you may be using a memory location already in use by your software storing some essential data and you are unknowingly modifying it. You may be writing your own code and data.
Such bugs and errors created by the pointers may not show up immediately but come up later and it is at that time difficult to predict that it was the pointer to blamed.
Due to these drawbacks of pointers, the Programming language like JAVA, C# cannot allow pointer operation.