Address of a variable in c :
Location in a memory where a variable stores its data or value is known as address of variable. To know address of any variable c has provided a special unary operator & which is known as dereferencing operator or address operator. It operator is only used with variables not with the constant. For example:
#include<stdio.h>
int main(){
int a=5;
printf("Address of variable a is: %d",&a);
return 0;
}
We cannot write: &&a, because:
&&a=& (&a) =& (address of variable a) =& (a constant number)
And we cannot use address operator with constant.
Important points about address of variables in c:
(1)Address of any variable in c is an unsigned integer. It cannot be a negative number. So in printf statement we should use %u instead of %d, to print the address of any variable.
%d: It is used to print signed decimal number.
%u: It is used to print unsigned decimal number.
Since, if the address of any variable will beyond the range of signed short int it will print a cyclic value.
(2)Address of any variable must be within the range 0000 to FFFF in hexadecimal number format or 0 to 65535 i.e. range of unsigned short int in c. To print the address of any variable in hexadecimal number format by printf function we should use %x or %X.
%x: To print a number in hexadecimal format using 0 to 9 and a, b, c, d, e, f.
%X: To print a number in hexadecimal format using 0 to 9 and A, B, C, D, E, F.
(3)A programmer cannot know at which address a variable will store the data. It is decided by compiler or operating system.
(4)Any two variables in c cannot have same physical address.
(5)Address of any variable reserve two bytes of memory spaces.
(6) Address of any variable in c is not integer type so to assign an address to a integral variable we have to type cast the address. For example:
#include<stdio.h>
int main(){
int a=100;
unsigned int b=(unsigned)&b;
printf("%u",b);
return 0;
}
Address arithmetic in c:
(1) We can subtract address of any two variables. For example:
#include<stdio.h>
int main(){
int a;
int b;
printf("%d",&b-&a);
return 0;
}
(2)We cannot add, multiply, divide two addresses.
(3) we can add or subtract a integer number with address.
(3)Other operators which can be used with addresses are:
(a)Negation operator:!
(b)Size operator: sizeof
(c)Type casting operator: (Type)
(e) Dereferencing operator: *
(f)Logical operator: &&, ||
Example:
#include<stdio.h>
int main(){
int a=12;
printf("%d",!&a);
printf("%d",sizeof(&a));
printf("%d",(int)&a);
printf("%d",*&a);
printf("%d %d %d %d",&a&&&b,&a&&b,&a||&b,&a||b);
return 0;
}
No comments:
Post a Comment