Published on Oct 09,2014
953 Views
Email Post


Pointers in C are easy and fun to learn. Pointers are the powerful feature in C and differs from other popular programming languages like Java and Visual Basic. Some C programming tasks are done easily with pointers. A pointer variable is used to store the address of another variable. They “point” to the locations in memory.

C Pointer Syntax:

<data-type>*<variable-name>;
Int*p;/

*p is a pointer to int type variable  */. And p is going to store the address of a memory location containing the integer number.

Where to Use Unary Operators?

  • Unary operator ‘&’ is used to get the address of any variable.
  • Unary operator ‘*’ dereferences the address stored in the pointer to access the data the pointer points to.

Simple Example to Explain Integer Pointers:

#include<stdio.h>
Int main()
{
Int a=10;
Int *ptr=&a;
Printf(“ptr:%x\n”,ptr);
System(“pause”);
Return 0;
}

The output is ‘28ff44’

In order to dereference ptr, the following is done:

#include<stdio.h>
Int main()
{
Int a=10;
Int *ptr=&a;
Printf(“ptr:%x\n”,ptr);
Printf(“ptr:%d\n”,*ptr);
System(“pause”);
Return 0;
}

This gives the output ‘10’

#include<stdio.h>
Int main()
{
Int a=10;
Int *ptr=&a;
Printf(“ptr:%x\n”,ptr);
Printf(“ptr:%d\n”,*ptr);
*ptr +=20;
Printf(“ptr:%d\n”,a);
System(“pause”);
Return 0;
}

This gives the result ‘a=30’.

Example to Explain Character & Integer Pointers Together:

#include<stdio.h>
Int main()
{
Int a=10;
Char ch=’c’;
Int *ptr=&a;
Char * cptr=&ch;
Printf(“ptr:%x\n”,ptr);
Printf(“ptr:%d\n”,*ptr);
*ptr +=20;
Printf(“ptr:%d\n”,a);
Printf(“size of int  ptr: %d\n”, sizeof(ptr));
Printf(“size of char ptr:%d\n”,sizeof(cptr));
System(“pause”);
Return 0;
}

The output is ‘size of int ptr: 4’ and ‘size of char ptr:4’.

Got a question for us? Please mention them in the comments section and we will get back to you. 

Related Posts:

C & Data Structures

Explaining External Variables in C

About Author
edureka
Published on Oct 09,2014

Share on

Browse Categories

Comments
2 Comments