Best and Easy way explain Pointers in C Programming with examples

Best and Easy way explain Pointers in C Programming with examples



A pointer is a variable that stores the address of another variable. Unlike other variables that hold values of a certain type, pointer holds the address of a variable. For example, an integer variable holds (or you can say stores) an integer value, however an integer pointer holds the address of a integer variable.


Best Example

#include <stdio.h>
int main()
{
   /* Pointer of integer type, this can hold the
    * address of a integer type variable.
    */
   int *p;

   int var = 10;

   /* Assigning the address of variable var to the pointer
    * p. The p can hold the address of var because var is
    * an integer type variable.
    */
   p= &var;

   printf("Value of variable var is: %d", var);
   printf("\nValue of variable var is: %d", *p);
   printf("\nAddress of variable var is: %p", &var);
   printf("\nAddress of variable var is: %p", p);
   printf("\nAddress of pointer p is: %p", &p);
   return 0;
}

Output:
Value of variable var is: 10
Value of variable var is: 10
Address of variable var is: 0x7fff5ed98c4c
Address of variable var is: 0x7fff5ed98c4c
Address of pointer p is: 0x7fff5ed98c50

Some Extra On Array:
We can also declare a pointer of type int to point to the array arr.
int *p;
p = arr;  
// or, 
p = &arr[0];    //both the statements are equivalent.

Pointer to Array

As studied above, we can use a pointer to point to an array, and then we can use that pointer to access the array elements. Lets have an example,
#include <stdio.h>

int main()
{
    int i;
    int a[5] = {1, 2, 3, 4, 5};
    int *p = a;     // same as int*p = &a[0]
    for (i = 0; i < 5; i++)
    {
        printf("%d", *p);
        p++;
    }
    
    return 0;
}
Best and Easy way explain Pointers in C Programming with examples Best and Easy way explain Pointers in C Programming with examples Reviewed by Anonymous on November 29, 2018 Rating: 5

No comments:

Java Ternary Operator

Java Ternary Operator Java ternary operator is the only conditional operator that takes three operands. Java ternary operator is a one l...

Powered by Blogger.