Difference between revisions of "Interview Preparation topic : Pointers in C"

From Embedded Systems Learning Academy
Jump to: navigation, search
Line 24: Line 24:
 
  type *pointer;<br>
 
  type *pointer;<br>
 
Where type can be int, double, float, char and pointer can be any variable.
 
Where type can be int, double, float, char and pointer can be any variable.
 +
<br>
 +
<br>
 +
<br>
 +
Consider the following example:<br>
 +
 +
 +
#include <stdio.h>
 +
 +
int main () {
 +
 +
  int  temp= 20;  /* Stores the value 20 in variable temp */
 +
  int  *ip;        /* Declares a pointer variable of type int */
 +
 +
  ip = &temp;  /*store address of temp in pointer variable, so now the address of temp will be in ip */
 +
 +
  printf("Address of temp variable: %x\n", &temp);  /* print the address of variable temp */
 +
 +
 
 +
  printf("Address stored in ip variable: %x\n", ip ); /* prints the address stored in variable ip */
 +
 +
 +
  printf("Value of *ip variable: %d\n", *ip );      /* prints the value stored at address ip, this is also known as dereferencing of a pointer */
 +
 +
  return 0;
 +
}

Revision as of 22:55, 10 December 2016

What is a Pointer?

A pointer is a variable which contains the address in memory of another variable. Every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory.

Lets Look at the following example:

  1. include <stdio.h>

int main ()

{
  int  temp;
  int temp1;
  printf("Address of temp variable: %x\n", &temp );
  printf("Address of temp1 variable: %x\n", &temp1 );
  return 0;

}

When the following code is compiled and executed:

Address of temp variable: edf53400
Address of temp1 variable: adf9a5f6


To declare a pointer to a variable do:

type *pointer;

Where type can be int, double, float, char and pointer can be any variable.


Consider the following example:


  1. include <stdio.h>

int main () {

  int  temp= 20;   /* Stores the value 20 in variable temp */
  int  *ip;        /* Declares a pointer variable of type int */
  ip = &temp;  /*store address of temp in pointer variable, so now the address of temp will be in ip */
  printf("Address of temp variable: %x\n", &temp);  /* print the address of variable temp */


  printf("Address stored in ip variable: %x\n", ip ); /* prints the address stored in variable ip */


  printf("Value of *ip variable: %d\n", *ip );       /* prints the value stored at address ip, this is also known as dereferencing of a pointer */
  return 0;

}