Pointer in C
3rd Mar 2010 at 9:16 AM | Posted in C - Pointer Concept, C-Language | Leave a comment& – “address of” operator.
* – “value at address” operator.
main()
{
int i = 3 ;
printf ("\nAddress of i = %u", &i);
printf ("\nValue of i = %d", i);
printf ("\nValue of i = %d", *(&i));
}
The output of the above program would be:
Address of i = 65524
Value of i = 3
Value of i = 3
Explaination:
%u – is format specifier for unsigned decimal integer.
&i – is address of i
%d – is format specifier for signed decimal integer.
i – is variable of integer type. It contain value 3.
*(&i) – is value at adress (&i). More clearly value at adress 65524.
Now declearation of pointer:
int *alpha ; //alpha is a pointer of type integer
char *ch ; //ch is a character type pointer
float *s ; //s is a pointer of type float
The declaration float *s does not mean that s is going to contain a floating-point value. What it means is, s is going to contain the address of a floating-point value. Similarly, char *ch means that ch is going to contain the address of a char value. Or in other words, the value at address stored in ch is going to be a char.
int i, *j, **k ;
Here k is a pointer to an integer pointer.
main()
{
int i = 3, *j, **k ;
j = &i ;
k = &j ;
printf ("\nAddress of i = %u", &i);
printf ("\nAddress of i = %u", j);
printf ("\nAddress of i = %u", *k);
printf ("\nAddress of j = %u", &j);
printf ("\nAddress of j = %u", k);
printf ("\nAddress of k = %u", &k);
printf ("\nValue of j = %u", j);
printf ("\nValue of k = %u", k);
printf ("\nValue of i = %d", i);
printf ("\nValue of i = %d", * (&i));
printf ("\nValue of i = %d", *j);
printf ("\nValue of i = %d", **k);
}
The output of the above program would be:
Address of i = 65524
Address of i = 65524
Address of i = 65524
Address of j = 65522
Address of j = 65522
Address of k = 65520
Value of j = 65524
Value of k = 65522
C Program-Call By value& Call By Reference(Swaping Program)
3rd Mar 2010 at 9:02 AM | Posted in C - Pointer Concept | 1 CommentSwap program:
Call By Value:
void swapv(int x, int y); //prototype declaration
main( )
{
int a = 10, b = 20 ;
swapv ( a, b ) ;
printf ( "\na = %d b = %d", a, b ) ;
}
swapv ( int x, int y )
{
int t ;
t = x ;
x = y ;
y = t ;
printf ( "\nx = %d y = %d", x, y ) ;
}
Outpot:
x = 20 y = 10
a = 10 b = 20
Call By Reference:
void swapr(int *x, int *y); //prototype declaration
main( )
{
int a = 10, b = 20 ;
swapr ( &a, &b ) ; //sending the address of a and b
printf ( "\na = %d b = %d", a, b ) ;
}
swapr( int *x, int *y ) //*x is taking value at address send by &a, *y is taking value at address send by &b
{
int t ;
t = *x ;
*x = *y ;
*y = t ;
}
Outpot:
a = 20 b = 10
here we send the address of a and b.
Then just swap the value at these addresses.
Blog at WordPress.com. | Theme: Pool by Borja Fernandez.
Entries and comments feeds.
