Wednesday 31 May 2017

Pointer to Structure in C ~ GNIITHELP

Pointer to Structure

Like we have array of integers, array of pointer etc, we can also have array of structure variables. And to make the use of array of structure variables efficient, we use pointers of structure type. We can also have pointer to a single structure variable, but it is mostly used with array of structure variables.
struct Book
{
 char name[10];
 int price;
}

int main()
{
 struct Book a;       //Single structure variable
 struct Book* ptr;    //Pointer of Structure type
 ptr = &a;
 
 struct Book b[10];     //Array of structure variables
 struct Book* p;        //Pointer of Structure type
 p = &b;    
}

Pointer to Structures

Accessing Structure Members with Pointer

To access members of structure with structure variable, we used the dot . operator. But when we have a pointer of structure type, we use arrow -> to access structure members.
struct Book
{
 char name[10];
 int price;
}

int main()
{
 struct Book b;
 struct Book* ptr = &b;   
 ptr->name = "Dan Brown";      //Accessing Structure Members
 ptr->price = 500;
}

Read More »

Pointer to Array in C ~ GNIITHELP

Pointer and Arrays

When an array is declared, compiler allocates sufficient amount of memory to contain all the elements of the array. Base address which gives location of the first element 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 byte, the five element will be stored as follows
address of array
Here variable arr will give the base address, which is a constant pointer pointing to the element, arr[0]. Therefore arr is containing the address of arr[0] i.e 1000.
 arr is equal to &arr[0]   // by default
We can 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.
Now we can access every element of array arr using p++ to move from one element to another.
NOTE : You cannot decrement a pointer once incremented. p-- won't work.

Pointer to Array

As studied above, we can use a pointer to point to an Array, and then we can use that pointer to access the array. Lets have an example,
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++;
}
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 pointer and print all the values.
Array using pointer tips

Pointer to Multidimensional Array

A multidimensional array is of form, a[i][j]. Lets see how we can make a pointer point to such an array. As we know now, 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.
*(*(ptr + i) + j)
is same as
a[i][j]

Pointer and Character strings

Pointer can also be used to create strings. Pointer variables of char type are treated as string.
char *str = "Hello";
This creates a string and stores its address in the pointer variable str. The pointer str now points to the first character of the string "Hello". Another important thing to note that string created using char pointer can be assigned a value at runtime.
char *str;
str = "hello";   //thi is Legal
The content of the string can be printed using printf() and puts().
printf("%s", str);
puts(str);
Notice that str is pointer to the string, it is also name of the string. Therefore we do not need to use indirection operator *.

Array of Pointers

We can also have array of pointers. Pointers are very helpful in handling character array with rows of varying length.
char *name[3]={ 
  "Adam",
  "chris",
  "Deniel"
              };
//Now see same array without using pointer
char name[3][20]= { 
      "Adam",
      "chris",
      "Deniel"
                 };
Pointer with character array in c
In the second approach memory wastage is more, hence it is prefered to use pointer in such cases.

Read More »

Declaring and initializing pointer in C ~ GNIITHELP

Declaring a pointer variable

General syntax of pointer declaration is,
data-type *pointer_name;
Data type of pointer must be same as the variable, which the pointer is pointing. void type pointer works with all data types, but isn't used oftenly.

Initialization of Pointer variable

Pointer Initialization is the process of assigning address of a variable to pointer variable. Pointer variable contains address of variable of same data type. In C language address operator & is used to determine the address of a variable. The & (immediately preceding a variable name) returns the address of the variable associated with it.
int a = 10 ;
int *ptr ;        //pointer declaration
ptr = &a ;        //pointer initialization
or,
int *ptr = &a ;      //initialization and declaration together
Pointer variable always points to same type of data.
float a;
int *ptr;
ptr = &a;    //ERROR, type mismatch


Dereferencing of Pointer

Once a pointer has been assigned the address of a variable. To access the value of variable, pointer is dereferenced, using the indirection operator *.


int a,*p;
a = 10;
p = &a;   

printf("%d",*p);    //this will print the value of a. 

printf("%d",*&a);  //this will also print the value of a.

printf("%u",&a);  //this will print the address of a.

printf("%u",p);  //this will also print the address of a.

printf("%u",&p);  //this will also print the address of p.
Read More »

Pointers concept in C ~ GNIITHELP

Introduction to Pointers

Pointers are variables that hold address of another variable of same data type.
Pointers are one of the most distinct and exciting features of C language. It provides power and flexibility to the language. Although pointer may appear little confusing and complicated in the beginning, but trust me its a powerful tool and handy to use once its mastered.

Benefit of using pointers

  • Pointers are more efficient in handling Array and Structure.
  • Pointer allows references to function and thereby helps in passing of function as arguments to other function.
  • It reduces length and the program execution time.
  • It allows C to support dynamic memory management.

Concept of Pointer

Whenever a variable is declared, system will allocate a location to that variable in the memory, to hold value. This location will have its own address number.
Let us assume that system has allocated memory location 80F for a variable a.
int a = 10 ;
storage of variable in C
We can access the value 10 by either using the variable name a or the address 80F. Since the memory addresses are simply numbers they can be assigned to some other variable. The variable that holds memory address are called pointer variables. A pointer variable is therefore nothing but a variable that contains an address, which is a location of another variable. Value of pointer variable will be stored in another memory location.
Pointer to a variable

Read More »

Unions in C ~ GNIITHELP

Unions in C Language

Unions are conceptually similar to structures. The syntax of union is also similar to that of structure. The only differences is in terms of storage. In structure each member has its own storage location, whereas all members of union uses a single shared memory location which is equal to the size of its largest data member.
union and structure comparison
This implies that although a union may contain many members of different types, it cannot handle all the members at same time. A union is declared using union keyword.
union item
{
 int m;
 float x;
 char c;
}It1;
This declares a variable It1 of type union item. This union contains three members each with a different data type. However only one of them can be used at a time. This is due to the fact that only one location is allocated for a union variable, irrespective of its size. The compiler allocates the storage that is large enough to hold largest variable type in the union. In the union declared above the member x requires 4 bytes which is largest among the members in 16-bit machine. Other members of union will share the same address.

Accessing a Union Member

Syntax for accessing union member is similar to accessing structure member,
union test
{
 int a;
 float b;
 char c;
}t;

t.a ;     //to access members of union t 
t.b ;     
t.c ;     

Complete Example for Union

#include <stdio.h>
#include <conio.h>

union item
{
 int a;
 float b;
 char ch;
};

int main( )
{
 union item it;
 it.a = 12;
 it.b = 20.2;
 it.ch='z';
 clrscr();
 printf("%d\n",it.a);
 printf("%f\n",it.b);
 printf("%c\n",it.ch);
 getch();
 return 0;
}
Output
-26426      
20.1999     
z
As you can see here, the values of a and b get corrupted and only variable c prints the expected result. Because in union, the only member whose value is currently stored will have the memory.

Read More »

typedef in C ~ GNIITHELP

typedef

typedef is a keyword used in C language to assign alternative names to existing types. Its mostly used with user defined data types, when names of data types get slightly complicated. Following is the general syntax for using typedef,
typedef existing_name alias_name
Lets take an example and see how typedef actually works.
typedef unsigned long ulong;
The above statement define a term ulong for an unsigned long type. Now this ulong identifier can be used to define unsigned long type variables.
ulong i, j ;

Application of typedef

typedef can be used to give a name to user defined data type as well. Lets see its use with structures.
typedef struct
{
  type member1;
  type member2;
  type member3;
} type_name ;
Here type_name represents the stucture definition associated with it. Now this type_name can be used to declare a variable of this stucture type.
type_name t1, t2 ;

Example of structure definition using typedef

#include<stdio.h>
#include<conio.h>
#include<string.h>
 
typedef struct employee
{
 char  name[50];
 int   salary;
} emp ;
 
void main( )
{
 emp e1;
 printf("\nEnter Employee record\n");
 printf("\nEmployee name\t");
 scanf("%s",e1.name);
 printf("\nEnter Employee salary \t");
 scanf("%d",&e1.salary);
 printf("\nstudent name is %s",e1.name);
 printf("\nroll is %d",e1.salary);
 getch();
}

typedef and Pointers

typedef can be used to give an alias name to pointers also. Here we have a case in which use of typedef is beneficial during pointer declaration.
In Pointers * binds to the right and not the left.
int* x, y ;
By this declaration statement, we are actually declaring x as a pointer of type int, whereas y will be declared as a plain integer.
typedef int* IntPtr ;
IntPtr x, y, z;
But if we use typedef like in above example, we can declare any number of pointers in a single statement.
NOTE : If you do not have any prior knowledge of pointers, do study Pointers first.

Read More »

Introduction to Structure in C ~ GNIITHELP

Introduction to Structure

Structure is a user-defined data type in C which allows you to combine different data types to store a particular type of record. Structure helps to construct a complex data type in more meaningful way. It is somewhat similar to an Array. The only difference is that array is used to store collection of similar datatypes while structure can store collection of any type of data.
Structure is used to represent a record. Suppose you want to store record of Student which consists of student name, address, roll number and age. You can define a structure to hold this information.

Defining a structure

struct keyword is used to define a structure. struct define a new data type which is a collection of different type of data.
Syntax :
struct structure_name
{
 //Statements
};

Example of Structure

struct Book
{
 char name[15];
 int price;
 int pages;
};
Here the struct Book declares a structure to hold the details of book which consists of three data fields, namely nameprice and pages. These fields are called structure elements or members. Each member can have different data type,like in this case, name is of char type and price is of int type etc. Book is the name of the structure and is called structure tag.

Declaring Structure Variables

It is possible to declare variables of a structure, after the structure is defined. Structure variable declaration is similar to the declaration of variables of any other data types. Structure variables can be declared in following two ways.

1) Declaring Structure variables separately

struct Student
{
 char[20] name;
 int age;
 int rollno; 
} ;

struct Student S1 , S2;   //declaring variables of Student

2) Declaring Structure Variables with Structure definition

struct Student
{
 char[20] name;
 int age;
 int rollno; 
} S1, S2 ;
Here S1 and S2 are variables of structure Student. However this approach is not much recommended.

Accessing Structure Members

Structure members can be accessed and assigned values in number of ways. Structure member has no meaning independently. In order to assign a value to a structure member, the member name must be linked with the structure variable using dot . operator also called period or member access operator.
struct Book
{
 char name[15];
 int price;
 int pages;
} b1 , b2 ;

b1.price=200;      //b1 is variable of Book type and price is member of Book
We can also use scanf() to give values to structure members through terminal.
scanf(" %s ", b1.name);
scanf(" %d ", &b1.price);

Structure Initialization

Like any other data type, structure variable can also be initialized at compile time.
struct Patient
{
 float height;
 int weight;  
 int age; 
};

struct Patient p1 = { 180.75 , 73, 23 };    //initialization
or
struct patient p1;
p1.height = 180.75;     //initialization of each member separately
p1.weight = 73;
p1.age = 23;

Array of Structure

We can also declare an array of structure. Each element of the array representing a structure variable. Example : struct employee emp[5];
The above code define an array emp of size 5 elements. Each element of array emp is of type employee
#include<stdio.h>
#include<conio.h>
struct employee
{
 char ename[10];
 int sal;
};

struct employee emp[5];
int i,j;
void ask()
{
 for(i=0;i<3;i++)
 {
  printf("\nEnter %dst employee record\n",i+1);
  printf("\nEmployee name\t");
  scanf("%s",emp[i].ename);
  printf("\nEnter employee salary\t");
  scanf("%d",&emp[i].sal);
 }
 printf("\nDisplaying Employee record\n");
 for(i=0;i<3;i++)
 {
  printf("\nEmployee name is %s",emp[i].ename);
  printf("\nSlary is %d",emp[i].sal);
 }
}
void main()
{
 clrscr();
 ask();
 getch();
}

Nested Structures

Nesting of structures, is also permitted in C language.
Example :
struct student
{
 char[30] name;
 int age;
   struct address
    {
     char[50] locality;
     char[50] city;
     int pincode;  
    };
}; 


Structure as function arguments

We can pass a structure as a function argument in similar way as we pass any other variable or array.
Example :
#include<stdio.h>
#include<conio.h>
struct student
{
 char name[10];
 int roll;
};
void show(struct student st);
void main()
{
 struct student std;
 clrscr();
 printf("\nEnter student record\n");
 printf("\nstudent name\t");
 scanf("%s",std.name);
 printf("\nEnter student roll\t");
 scanf("%d",&std.roll);
 show(std);
 getch();
}

void show(struct student st)
{
 printf("\nstudent name is %s",st.name);
 printf("\nroll is %d",st.roll);
}

Read More »

Passing Array to function in C ~ GNIITHELP

Passing Array to Function

Whenever we need to pass a list of elements as argument to the function, it is prefered to do so using an array. But how can we pass an array as argument ? Lets see how to do it.

Declaring Function with array in parameter list

There are two possible ways to do so, one will lead to call by value and the other is used to perform call be reference.
  • We can either have an array in parameter.
    int sum (int arr[]);
    
  • Or, we can have a pointer in the parameter list, to hold base address of array.
    int sum (int* ptr);
    
    We will study this in detail later when we will study pointers.

Returning Array from function

We dont't return an array from functions, rather we return a pointer holding the base address of the array to be returned. But we must, make sure that the array exists after the function ends.
int* sum (int x[])
{
 //statements
 return x ;
}
We will discuss about this when we will study pointers with arrays.

Example : Create a function to sort an Array of elements

void sorting(int x[],int y)
{
 int i, j, temp ;
 for(i=1; i<=y-1; i++)
 {
  for(j=0; j< y-i; j++)
  {
   if(x[j] > x[j+1])
   {
    temp = x[j];
    x[j] = x[j+1];
    x[j+1] = temp;
   }
  }
 }
 for(i=0;i<5;i++)
 {
  printf("\t%d",x[i]);
 }
}
In the above example,
  • return type is void, that means function does not return any thing.
  • Sorting is the function name.
  • int x[ ] and int y is the parameter list.
  • int i, j, temp inside curly braces are the local variable declaraction.
Read More »

Types of Function calls in C ~ GNIITHELP

Types of Function calls in C

Functions are called by their names. If the function is without argument, it can be called directly using its name. But for functions with arguments, we have two ways to call them,
  1. Call by Value
  2. Call by Reference

Call by Value

In this calling technique we pass the values of arguments which are stored or copied into the formal parameters of functions. Hence, the original values are unchanged only the parameters inside function changes.
void calc(int x);
int main()
{
 int x = 10;
 calc(x);
 printf("%d", x);
}

void calc(int x)
{
 x = x + 10 ;
}
Output : 10
In this case the actual variable x is not changed, because we pass argument by value, hence a copy of x is passed, which is changed, and that copied value is destroyed as the function ends(goes out of scope). So the variable x inside main() still has a value 10.
But we can change this program to modify the original x, by making the function calc() return a value, and storing that value in x.
int calc(int x);
int main()
{
 int x = 10;
 x = calc(x);
 printf("%d", x);
}

int calc(int x)
{
 x = x + 10 ;
 return x;
}
Output : 20

Call by Reference

In this we pass the address of the variable as arguments. In this case the formal parameter can be taken as a reference or a pointer, in both the case they will change the values of the original variable.
void calc(int *p);
int main()
{
 int x = 10;
 calc(&x);     // passing address of x as argument
 printf("%d", x);
}

void calc(int *p)
{
 *p = *p + 10;
}
Output : 20
NOTE : If you do not have a prior knowledge of pointers, do study Pointers first.

Read More »

Functions in C ~ GNIITHELP

Functions in c

A function is a block of code that performs a particular task. There are times when we need to write a particular block of code for more than once in our program. This may lead to bugs and irritation for the programmer. C language provides an approach in which you need to declare and define a group of statements once and that can be called and used whenever required. This saves both time and space.
C functions can be classified into two categories,
  • Library functions
  • User-defined functions
types of functions in C
Library functions are those functions which are defined by C library, example printf()scanf()strcat() etc. You just need to include appropriate header files to use these functions. These are already declared and defined in C libraries.
User-defined functions are those functions which are defined by the user at the time of writing program. Functions are made for code reusability and for saving time and space.

Benefits of Using Functions

  1. It provides modularity to the program.
  2. Easy code Reuseability. You just have to call the function by its name to use it.
  3. In case of large programs with thousands of code lines, debugging and editing becomes easier if you use functions.

Function declaration

General syntax of function declaration is,
return-type function-name (parameter-list) ;
Like variable and an array, a function must also be declared before its called. A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately. A function declaration consist of 4 parts.
  • return-type
  • function name
  • parameter list
  • terminating semicolon

Function definition Syntax

General syntax of function definition is,
return-type function-name (parameter-list)
{
  function-body ;
}
The first line return-type function-name(parameter) is known as function header and the statement within curly braces is called function body.

return-type

return type specifies the type of value(int,float,char,double) that function is expected to return to the program calling the function.

function-name

function name specifies the name of the function. The function name is any valid C identifier and therefore must follow the same rule of formation as other variables in C.

parameter-list

The parameter list declares the variables that will receive the data sent by calling program. They often referred to as formal parameters. These parameters are also used to send values to calling program.

function-body

The function body contains the declarations and the statement(algorithm) necessary for performing the required task. The body is enclosed within curly braces { } and consists of three parts.
  • local variable declaration.
  • function statement that performs the tasks of the function.
  • return statement that return the value evaluated by the function.

Functions and Arguments

Arguments are the values specified during the function call, for which the formal parameters are declared in the function.
functions and arguments in C

Example : Function that return some value

#include<stdio.h>
#include<conio.h>
int larger(int a,int b);    // function declaration

void main()
{
 int i,j,k;
 clrscr();
 i=99;
 j=112;
 k=larger(i,j);       // function call
 printf("%d",k);
 getch();
}

int larger(int a,int b)     // function declaration
{
 if(a>b)
 return a;
 else
 return b;
}

Nesting of Functions

C language also allows nesting of functions, one function using another function inside its body. We must be careful while using nested functions, because it may lead to infinte nesting.
function1()
{
   function2() ;
   //statements
} 
If function2 calls function1 inside it, then in this case it will lead to infinite nesting, they will keep calling each other. Hence we must be careful.

Recursion

Recursion is a special of nesting functions, where a function calls itself inside it. We must have certain condition to break out of the recursion, otherwise recursion is infinite.
function1()
{
   function1() ;
   //statements
}

Example : Factorial of a number using Recursion

#include<stdio.h>
#include<conio.h>
int factorial(int x);

void main()
{
 int a,b;
 clrscr();
 printf("Enter no.");
 scanf("%d",&a);
 b=factorial(a);
 printf("%d",b);
 getch();
}

int factorial(int x)
{
 int r=1;
 if(x==1) return 1;
 else r=x*factorial(x-1);
 return r;
}

Read More »