Best Industrial Training in C,C++,PHP,Dot Net,Java in Jalandhar

Tuesday, 21 January 2014

Read Pointers in C

How to read complex pointers in C Programming?

Rule 1. Assign the priority to the pointer declaration considering precedence and associative according to following table.
 Where

(): This operator behaves as bracket operator or function operator.

[]: This operator behaves as array subscription operator.

*: This operator behaves as pointer operator not as multiplication operator.

Identifier: It is not an operator but it is name of pointer variable. You will always find the first priority will be assigned to the name of pointer.

Data type: It is also not an operator. Data types also includes modifier (like signed int, long double etc.)

You will understand it better by examples:

(1) How to read following pointer?

char (* ptr)[3]
Answer:

Step 1: () and [] enjoys equal precedence. So rule of associative will decide the priority. Its associative is left to right So first priority goes to ().



Step 2: Inside the bracket * and ptr enjoy equal precedence. From rule of associative (right to left) first priority goes to ptr and second priority goes to *.

Step3: Assign third priority to [].

Step4: Since data type enjoys least priority so assign fourth priority to char.

Now read it following manner:

ptr is pointer to such one dimensional array of size three which content char type data.

 

Rule 2: Assign the priority of each function parameter separately and read it also separately.
Understand it through following example.

(3) How to read following pointer?
void (*ptr)(int (*)[2],int (*) void))
Answer:

Assign the priority considering rule of precedence and associative.



Now read it following manner:

ptr is pointer to such function which first parameter is pointer to one dimensional array of size two which content int type data and second parameter is pointer to such function which parameter is void and return type is int data type and return type is void.

 Pointer : Accessing Value from Address in C

#include<stdio.h>
main( )
{
int i = 3 ;
int *j ;
j = &i ;
printf ( "nAddress of i = %u", &i ) ;
printf ( "nAddress of i = %u", j ) ;
printf ( "nAddress of j = %u", &j ) ;
printf ( "nValue of j = %u", j ) ;
printf ( "nValue of i = %d", i ) ;
printf ( "nValue of i = %d", *( &i ) ) ;
printf ( "nValue of i = %d", *j ) ;
}

Output:

Address of i = 65524
Address of i = 65524
Address of j = 65522
Value of j = 65524
Value of i = 3
Value of i = 
Value of i = 3
 
 
 
 

How to Access Address of Variable using Pointer

Program :

#include<stdio.h>
   void main( )
  {
     int i = 3 ;  
printf("nAddress of i = %u", &i ) ;
printf("nValue of i = %d", i ) ;  
printf("nValue of i = %d", *( &i ) ) ;
}

Output:

Address of i = 65524 Value of i = 3 Value of i = 3

Explanation :

Variable ‘i’ is declared of type integer in the program , now suppose the integer variable can have value 3 stored inside it and it has address 65524.
  
 

Monday, 20 January 2014

Explain pointers in c



Pointer is a user defined data type which creates special types of variables which can hold the address of primitive data type likecharintfloatdouble or user defined data type like function, pointer etc. or derived data type like array, structure, union,enum.

Through pointers a developer can directly access memory from his/her code which makes memory related operations very fast. But, as always, with great power comes great responsibility.
A developer has to very carefully make use of pointers in order to avoid some problems that can be nightmare to debug.
Examples:

int *ptr;
int (*ptr)();
int (*ptr)[2];

In c programming every variable keeps two type of value.
1. Contain of variable or value of variable.
2. Address of variable where it has stored in the memory.

(1) Meaning of following simple pointer declaration and definition:
int a=5;
int * ptr;
ptr=&a;

Explanation:

About variable a:
1. Name of variable : a
2. Value of variable which it keeps: 5
3. Address where it has stored in memory : 1025 (assume)

About variable ptr:
4. Name of variable : ptr
5. Value of variable which it keeps: 1025
6. Address where it has stored in memory : 5000 (assume)

Pictorial representation:



Note: A variable where it will be stored in memory is decided by operating system. We cannot guess at which location a particular variable will be stored in memory.

(2) Meaning of following pointer declaration and definition:
int a=50;
int *ptr1;
int **ptr2;
ptr1=&a;
ptr2=&pt1;

Explanation: 

About variable a:
1. Name of variable : a
2. Value of variable which it keeps: 50
3. Address where it has stored in memory : 5000 (assume)

About variable ptr1:
4. Name of variable : ptr1
5. Value of variable which it keeps: 5000
6. Address where it has stored in memory : 9000 (assume)

About variable ptr2:
7. Name of variable : ptr2
8. Value of variable which it keeps: 9000
9. Address where it has stored in memory : 9555 (assume)

Pictorial representation of above pointer declaration and definition:


Note:
* is known as indirection operator which gives content of any variable.
& is known as reference operator which gives address where variable has stored in memory.

Cancellation rule of above two operators:
* and & operators always cancel to each other i.e.
*&p=p

But it is not right to write:
&*p=p

Simple example:

What will be output of following c program?
#include<stdio.h>
int main(){

    int x=25;
    int *ptr=&x; //statement one
    int **temp=&ptr; //statement two
    printf(“%d %d %d”.x.*ptr,**temp);
    return 0;
}

Output: 25 25 25
Explanation:
As we know value of variable x is 25.

*ptr= *(&x) //from statement one
=*&x
=x //using cancellation rule
=25

**temp= **(&ptr)=*(*&ptr)=*ptr=*(&x)=*&x=x=25

Storage Classes in C Programming Language

A storage class is an attribute that tells us where the variable would be stored, what will be the initial value of the variable if no value is assigned to that variable, life time of the variable and scope of the variable.

Syntax: storage_specifier data_type variable _name
There are four storage classes in C:
1) Automatic storage class
2) Register storage class
3) Static storage class
4) External storage class
There are 4 storage class specifiers available in C language. They are,

1. auto
2. extern
3. static
4. register

S.No.
Storage Specifier
Storage place
Initial / default value
Scope
Life
1
auto
CPU Memory
Garbage value
local
Within the function only.
2
extern
CPU memory
Zero
Global
Till the end of the main program. Variable definition might be anywhere in the C program
3
static
CPU memory
Zero
local
Retains the value of the variable between different function calls.
4
register
Register memory
Garbage value
local
Within the function

Note:

· For faster access of a variable, it is better to go for register specifiers rather than auto specifiers.

· Because, register variables are stored in register memory whereas auto variables are stored in main CPU memory.

· Only few variables can be stored in register memory. So, we can use variables as register that are used very often in a C program.




Automatic storage class:
The keyword used for Automatic storage class is 'auto'.
The variable declared as auto is stored in the memory.
Default value of that variable is garbage value.
Scope of that variable is local to the block in which the variable is defined.
Variable is alive till the control remains within the block in which the variable is defined.
Example:
#include<stdio.h>
#include<conio.h>
void main(){
auto int a;
printf(“%d”,a)
}
Output:
1285
As seen above, the output is garbage value.

Register storage class:
The keyword used for Register storage class is 'register'.
The variable declared as register is stored in the CPU register.
Default value of that variable is garbage value.
Scope of that variable is local to the block in which the variable is defined.
Variable is alive till the control remains within the block in which the variable is defined.
Main difference between auto and register is that variable declared as auto is stored in memory whereas variable declared as register is stored in CPU register. Since the variable is stored in CPU register, it takes very less time to access that variable. Hence it becomes very time efficient.
It is not necessary that variable declared as register would be stored in CPU registers. The number of CPU registers is limited. If the CPU register is busy doing some other task then variable might act as automatic variable.

Example:
#include<stdio.h>
#include<conio.h>
Void main(){
register int a;
printf(“%d”,a)
}
Output:
4587
As seen above, the output is garbage value.

Static storage class:
The keyword used for Static storage class is 'static'.
The variable declared as static is stored in the memory.
Default value of that variable is zero.
Scope of that variable is local to the block in which the variable is defined.
Life of variable persists between different function calls.

External storage class:
The keyword used for External storage class is 'extern'.
The variable declared as static is stored in the memory.
Default value of that variable is zero.
Scope of that variable is global.
Variable is alive as long as the program’s execution doesn’t come to an end.

External variable can be declared outside all the functions or inside function using 'extern' keyword.
Example:
#include<stdio.h>
#include<conio.h>
int a;
Void main(){
extern int b;
printf(“%d %d”,a,b)
}
int b=10;
Output:
0 10










Example program for auto variable in C:

#include<stdio.h>
void increment(void);
int main()
{
increment();
increment();
increment();
increment();
return 0;
}

void increment(void)
{
auto int i = 0 ;
printf ( "%d ", i ) ;
i++;
}

Output:
0 0 0 0

//C static example

#include<stdio.h>
void increment(void);
int main()
{
increment();
increment();
increment();
increment();
return 0;
}
void increment(void)
{
static int i = 0 ;
printf ( "%d ", i ) ;
i++;
}

Output:
0 1 2 3

Example program for extern variable in C:

The scope of this extern variable is throughout the main program. It is equivalent to global variable. Definition for extern variable might be anywhere in the C program.

#include<stdio.h>
int x = 10 ;
int main( )
{
extern int y ;
printf ( "The value of x is %d \n", x ) ;
printf ( "The value of y is %d",y ) ;
return 0;
}
int y = 50 ;

Output:
The value of x is 10
The value of y is 50

Example program for register variable in C:

Register variables are also local variables, but stored in register memory. Whereas, auto variables are stored in main CPU memory.
Register variables will be accessed very faster than the normal variables since they are stored in register memory rather than main memory.
But, only limited variables can be used as register since register size is very low. (16 bits, 32 bits or 64 bits)

#include <stdio.h>
int main()
{
register int i;
int arr[5]; // declaring array
arr[0] = 10; // Initializing array
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
for (i=0;i<5;i++)
{
// Accessing each variable
printf("value of arr[%d] is %d \n", i, arr[i]);
}
return 0;
}

Output:

value of arr[0] is 10

value of arr[1] is 20

value of arr[2] is 30

value of arr[3] is 40

value of arr[4] is 50


Friday, 17 January 2014

Program to sort set of strings in alphabetical order


#include<stdio.h>
#include<string.h>
void main()
{
char s[5][20],t[20];
int i,j;
clrscr();
printf("Enter any five strings : n");
for(i=0;i<5;i++)
    scanf("%s",s[i]);

for(i=1;i<5;i++)
    {
    for(j=1;j<5;j++)
        {
        if(strcmp(s[j-1],s[j])>0)
            {
            strcpy(t,s[j-1]);
            strcpy(s[j-1],s[j]);
            strcpy(s[j],t);
            }
        }
    }

printf("Strings in order are : ");
for(i=0;i<5;i++)
    printf("n%s",s[i]);
getch();
}

Program : C Program to Concat Two Strings without Using Library Function

#include<stdio.h>
#include<string.h>

void concat(char[],char[]);

void main()
{
char s1[50],s2[30];
printf("nEnter String 1 :");
gets(s1);
printf("nEnter String 2 :");
gets(s2);

concat(s1,s2);
printf("nConcated string is :%s",s1);
return(0);
}

void concat(char s1[],char s2[])
{
int i,j;

i = strlen(s1);

for(j=0; s2[j] != ''; i++,j++)
      s1[i]=s2[j];

s1[i]='';
}

Output of Program :

Enter String 1 : Pritesh
Enter String 2 : Taral
Concated string is : PriteshTaral

Explanation of Code :

Our program starts from main and we are accepting two strings from user using these following statements -
printf("nEnter String 1 :");
gets(s1);
printf("nEnter String 2 :");
gets(s2);
Inside the concate() function we are firstly calculating the size of first string.
i = strlen(s1);
Now we are iterating 2nd string character by character and putting each character to the end of the 1st string.

Explanation of Program With Dry Run :

Step 1 : Input
s1 = "Pritesh"
s2 = "Taral"
Step 2 : Size of Strings
i = strlen(s1);
  = strlen("Pritesh");
  = 7
Step 3 : Concatenating Strings
Last position of s1 = 7
First Character of the 2nd String will be stored at last Position of String 1. thus using for loop -
s1[7]  = "T"
s1[8]  = "a"
s1[9]  = "r"
s1[10] = "a"
s1[11] = "l"

With using User-defined Function Write a Program to Find Length of String

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

int FindLength(char str[]);      // Prototype Declaration

void main()
{
 char str[100];
 int length;
 printf("nEnter the String : ");
 gets(str);

 length = FindLength(str);

 printf("nLength of the String is : %d",length);
 getch();
}

//Writing function

int FindLength(char str[])
{
 int len = 0;
 while(str[len]!='\0')
    len++;
 return(len);
}