Monday, January 5, 2009

Pointers in 'c'

The pointers are used to point to a given location. They point to a location which contain the information of the datatype which is the datatype of its own. The pointer can be of any datatype used in ‘C’. It is represented like the declaration of the other variables but the difference is that it is preceded by an asterisk sign during declaration. During definition if the value is assigned to it then it is preceded by asterisk or if it is assigned the address then only the variable is given. The value of only the variable is equal to the value of the ordinary variable preceded by ampersand(&).
e.g. int *x;
This is declaration of pointer.
Let x be the normally declared variable and y be the pointer.
Int x;
Int *y;
X=5;-is the declaration of normal variable.
*y=5;-is the declaration of pointer variable.
X=*y;
Y=&x;
These are the relations of normal variable and pointer variable.
e.g.
void main()
{
Int x;
Int *y;
x=5;
*y=x;
Printf(“x=%dy=%d”,x,*y);
}
In the above program the value of both x and y will be same.i.e.5.
void main()
{
Int x;
Int *y;
x=5;
y=&x;
Printf(“x=%dy=%d”,x,*y);
}
In the above program also the value of both x and y will be same.i.e.5.
Now we will see how to accept the values in the pointer.
void main()
{
Int *y;
Printf(“Enter a value”);
Scanf(“%d”,y);
Printf(“%d”,*y);
Getch();
}
In the above program in scanf the instead of ‘&y’ we have used only ‘y’ which means that in pointer ‘y’ is equivalent to ‘&x’(where x is normal variable) and while printing instead of ‘y’ we give ‘*y’.
In array the array variable written alone serves as pointer. It points to the first variable of the array.
e.g.
int x[5];
if only x is used then it means that it is used as a pointer to the first number of the array.it is mostly used in functions when there is a need to send an array.
The array can be assigned to a single pointer value.
e.g. int x[5];
int *y;
y=x[];
Then accessing the other value of x is b incrementing the pointer by 2.
For float the incrementing is 2 and for character it is 1.

Watch tv!