Pointers store address of variables or a memory location.

// General syntax
datatype *var_name; 

// An example pointer "ptr" that holds
// address of an integer variable or holds
// address of a memory whose value(s) can
// be accessed as integer values through "ptr"
int *ptr;  

Using a Pointer:

To use pointers in C, we must understand below two operators.

  • To access address of a variable to a pointer, we use the unary operator (ampersand) that returns the address of that variable. For example &x gives us address of variable x.
// The output of this program can be different 
// in different runs. Note that the program 
// prints address of a variable and a variable 
// can be assigned different address in different 
// runs. 
#include <stdio.h> 

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

return 0; 
}
  • One more operator is unary * (Asterisk) which is used for two things :
    • To declare a pointer variable: When a pointer variable is declared in C/C++, there must be a * before its name.
// C program to demonstrate declaration of 
// pointer variables. 
#include <stdio.h> 
int main() 
{ 
    int x = 10; 
// 1) Since there is * in declaration, ptr 
// becomes a pointer varaible (a variable 
// that stores address of another variable) 
// 2) Since there is int before *, ptr is 
// pointer to an integer type variable 
int *ptr; 

// & operator before x is used to get address 
// of x. The address of x is assigned to ptr. 
ptr = &x; 

return 0; 
}
  • To access the value stored in the address we use the unary operator (*) that returns the value of the variable located at the address specified by its operand. This is also called Dereferencing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s