C Programming language

adplus-dvertising
C Pointer
Previous Home Next

Pointer is a address variable that hold the address of another variable. We can have a pointer to any variable type. The & is a unary operator that gives the address of a variable. The * (indirection or dereference operator), that gives the contents of an object that pointed to by a pointer.

To declare a pointer to a variable do:

data_type_name * variable name //Declare a pointer
int *ptr;

Example

main( )
{
int a = 5 ;
printf ( "\nAddress of a = %u", &a );
printf ( "\nValue of a = %d", a );
};

Output: The output of the above program would be:

address of a=1444

value of a=5

Look at the first printf( ) statement carefully. ‘&’ used in this statement is C’s ‘address of’ operator. The expression &a returns the address of the variable a, which in this case happens to be 1444 .Hence it is printed out using %u, which is a format specified for printing an unsigned integer.

The other pointer operator available in C is ‘*’, called ‘value at address’ operator. It gives the value stored at a particular address. The ‘value at address’ operator is also called ‘indirection’ operator. i.e showing in the program.

main()
{
int a = 5 ;
printf ( "\nAddress of a = %u", &a );
printf ( "\nValue of a = %d", a ) ;
printf ( "\nValue of a = %d", *( &a ) );
};

Output: The output of the above program would be:

Address of a = 1444

Value of a = 5

Value of a = 5

Another example of Pointer

#include <stdio.h>

int a, b;
int *p;

int main(void)
{
    a= 1;
    b = 2;
    p = &b;
    printf("\n");
    printf("a has the value %d and is stored at %u\n", a, (void *)&a);
    printf("b has the value %d and is stored at %u\n", b, (void *)&b);
    printf("p has the value %d and is stored at %u\n", p, (void *)&p);
    printf(" the value of the integer pointed to by p is
%u\n", *p);

    return 0;
};

Output: The output of the above program would be:

a has the value 1 and is stored at 170

b has the value 2 and is stored at 172

p has the value 00AC and is stored at 174

the value of the integer pointed to by p is 2

Note here (Void *): Pointers can also declare as a void. void pointers can't be dereference without explicit casting. this is because the compiler can't determine the size of the object. size of all type of pointer (near) in c is two byte either it is char pointer, double pointer, function pointer or null pointer. Void pointer is not exception of this rule and size of void pointer is also two byte.

Previous Home Next