Pointer in C - Computer for Competition Exams

Pointer in C

Pointer is an extremely powerful programming tool. A pointer is a variable which used to store the address of another variable of same  data type. It means that if we want to store the address of integer type then pointer type must be of integer and so on.
In C language, we have a special type of pointer named void (*), which contains the address of any type of variable. This pointer is also known as Generic Pointer.

Syntax :

      Data_type *Variable_name ;

     int *p ;
                             
Astrik (*) sign denotes that p is pointer variable not a normal variable.

Key Points :
  • Pointer contains the the address of another variable.
  • * sign denotes the pointer variable. It shows the value of the variables that address stored for a pointer variable.
  • To access address of a variable to a pointer, we use the unary operator (ampersand) that returns the address of that variable.
  • Pointer contains 2 bytes of memory for 16 bit processor.
  • If a pointer is assigned to NULL, it means it is pointing to nothing.
Example :


#include <stdio.h>

int main()
{
    int x;
    // Prints address of x
    printf("%p", &x);
    return 0;
}

Output :

0x7ffe6ee753ee

Example 2:

#include <stdio.h>

int main()
{
// A normal integer variable
int Var = 10;

// A pointer variable that holds address of var.
int *ptr = &Var;

// This line prints value at address stored in ptr.
// Value stored is value of variable "var"
printf("Value of Var = %d\n", *ptr);

// The output of this line may be different in different
// runs even on same machine.
printf("Address of Var = %p\n", ptr);

// We can also use ptr as lvalue (Left hand
// side of assignment)
*ptr = 20; // Value at address is now 20

printf("After doing *ptr = 20, *ptr is %d\n", *ptr);

return 0;
}

Output :

Value of Var = 10
Address of Var = 0x7ffc23954c74
After doing *ptr = 20, *ptr is 20

Array of Pointer :

There may be a situation when we want to maintain an array, which can store pointers to an int or char or any other data type available. Following is the declaration of an array of pointers to an integer −


int *ptr[con];

Example :

#include <stdio.h>
int main()
{
    // Declare an array
    int v[3] = {10, 100, 200};
    // Declare pointer variable
    int *ptr;
    // Assign the address of v[0] to ptr
    ptr = v;
    
     for (int i = 0; i < 3; i++)
    {
        printf("Value of *ptr = %d\n", *ptr);
        printf("Value of ptr = %p\n\n", ptr);
        // Increment pointer ptr by 1
        ptr++;
    }
}

Output :


Value of *ptr = 10

Value of ptr = 0x7ffcae30c710

Value of *ptr = 100
Value of ptr = 0x7ffcae30c714

Value of *ptr = 200
Value of ptr = 0x7ffcae30c718


Pointer in C Pointer in C Reviewed by Go Programming on July 21, 2017 Rating: 5
Powered by Blogger.