Thursday, October 29, 2009

Logical program 1:

#include < stdio.h >
int fun(char *str)
{
char *ptr=str;
while(*ptr++);
return ptr-str-1;
}
void main()
{
printf("%d",fun("selva"));
}


Output:

5

How ?

Pointer:
It stores another variable address. We can access that variable indirectly using pointer.
Eg:
int i;
int *j; // pointer variable declaration
j=&i; now address of i is stored in j ( & is"address of" operator)
consider
i address is 4001
so j =4001.

In program selva string will stored in *str pointer. Consider str address 1000
The string characters will store like this,


















100010011002100310041005
selva\0

char *ptr=str;
now ptr will store the str address i.e.,
ptr=1000
in while loop I used increment operation. It’ll first increment *ptr address and check the condition whether it’s null or not.
This loop will continue untill *ptr is null.


at first ptr=1000
after *ptr++ it will be ptr=1001 and *ptr=e
again ptr will increased ptr=1002 and *ptr=l
like that
ptr=1003 *ptr=v
ptr=1004 *ptr=a
ptr=1005 *ptr=\0
ptr=1006
now *ptr is null loop is come to end

ptr=1006 and str=1000

ptr-str-1
will produce 5.

0 comments:

Post a Comment