C Programming

Pointers

Posted on 20th October 2014

A pointer is a special type of variable that stores the memory address of another variable.

Pointer Declaration

Pointer declaration in C is similar to variable declaration except that the variable name is preceded with an asterisk(*). A pointer is also associated with a type which declares what type of value it points to.

Example

int *ptr;

In the above example ptr is the name given to the pointer. The * before ptr tells the compiler to treat it as a pointer variable. Finally the int declares that the pointer points to an integer variable.

Initializing a Pointer

A pointer is normally initialized using the & operator (address-of operator). The address-of operator returns the address of a variable.

Example

int i = 10;
int *ptr;

ptr = &i;

In the above example, the address of variable i is assigned to the pointer variable ptr.

Dereferencing a Pointer

The pointer variable ptr in the example above contains the memory address of variable i. The value stored in that memory address can be obtained by preceding the pointer variable with the * operator, as in *ptr. This is called dereferencing.

Example

#include <stdio.h>

int main()
{
 int i = 10;
 int *ptr;

 ptr = &i;
 printf("i = %d\n", i);
 printf("ptr = %x\n", ptr);
 printf("*ptr = %d\n", *ptr);

return 0;
}

The output of this program will be as below. Please note the value of ptr may change every time you execute the program as this is memory address of variable i

i = 10
ptr = 20fa50
*ptr = 10

Post a comment

Comments

Nothing yet..be the first to share wisdom.