Subscribe Us

What is Pointer in C programming language with example ? - smartduniya


I hope,You have already know the basic of C programming language, It helps you to understand pointer concept in C programming easily.

What is pointer in C programming language?

>> C pointer is a memory address. When you define a variable for example:

int x = 10;

You specify variable name (x), its data type (integer in this example) and its value is 10. The variable x resides in memory with a specified memory address. To get the memory address of variable x, you use operator & before it. This code snippet print memory address of x

printf("memory address of x is %d\n",&x;);

You get the output of this program

memory address of x is 1310588

Now you want to access memory address of variable x you have to use pointer. After that you can access and modify the content of memory address which pointer point to. In this case the memory address of x is 1310588 and its content is 10. To declare pointer you use asterisk notation (*) after pointer's data type and before pointer name as follows:

int *ptr;

Now if you want pointer px to points to memory address of variable x, you can use address-of operator (&) as follows:

int *ptr=&x;

After that you can change the content of variable x for example you can increase, decrease x value :

*ptr += 10;
printf("value of x is %d\n",x);
*ptr -= 5;
printf("value of x is %d\n",x);

and the output indicates that x variable has been change via pointer ptr.

value of x is 20
value of x is 15

It is noted that the operator (*) is used to dereference and return content of memory address.
In some programming contexts, you need a pointer which you can only change memory address of it but value or change the value of it but memory address.
In this cases, you can use const keyword to define a pointer points to a constant integer or a constant pointer points to an integer as follows

int c = 10;
int c2 = 20;
/* define a pointer and points to an constant integer. pc can point to another integer but you cannot change the content of it */
const int *pc = &c;
/* pc++; */ /* cause error */
printf("value of pc is %d\n",pc);
pc = &c2;
printf("value of pc is %d\n",pc);
/* define a constant pointer and points to an integer. py only can point to y and its memory address cannot be changed you can change its content */
int y = 10;
int y2 = 20;
int const *py = &y;
*py++;/* it is ok */
printf("value of y is %d\n",y);
/* py = &y2; */ /* cause error */

Output of this code is
value of pc is 1310580
value of pc is 1310576
value of y is 10

Post a Comment