C Tutorial
Control statement
C Loops
C Arrays
C String
C Functions
C Structure
C Pointer
C File
C Header Files
C Preprocessors
C Misc
About pointer in C language
Pointer in C is also called a variable which can store the address of other variable like int, char, array, float etc. They have a powerful features in C as well as C++ programming. In this guide we will learn about C pointer, its use and some very common mistakes of programmers when works with pointers.
How to declare a pointer in C?
We can use pointer to store address of any type of data. Here is some example of declaring pointer variable in C.
// syntax of pointer in c
int *x; // int pointer can store address of int
char *ch // can store address of character variable
float *age; // can store address of float data type
Now, let’s see how to store memory address of any data type to pointer. See the following example to store address in a pointer.
// storing address in a pointer
#include <stdio.h>
int main(){
int x, *y;
x = 5;
y = &x;
printf("%d\n", x);
printf("%p\n\n", y);
x = 10;
y = &x;
printf("%d\n", x);
printf("%p\n\n", y);
x = 50;
y = &x;
printf("%d\n", x);
printf("%p\n\n", y);
return 0;
}
See output:

The address may be different for your program. It depends on your memory as well as internal system.
C program to swap two number without third variable using pointer
In this program we will swap two number without a third variable using pointer in C. Let’s see the program bellow;
// C program to swap two number without third variable using pointer
#include<stdio.h>
int main(){
int x, y,*ptr1,*ptr2;
x = 20;
y = 30;
ptr1 = &x;
ptr2 = &y;
printf("Before swapping ...... \n*ptr1 = %d and *ptr2 = %d\n\n",*ptr1,*ptr2);
*ptr1=*ptr1+*ptr2;
*ptr2=*ptr1-*ptr2;
*ptr1=*ptr1-*ptr2;
printf("After swapping ...... \n*ptr1 = %d and *ptr2 = %d\n",*ptr1,*ptr2);
return 0;
}
Output of this program is as follows;

Some common mistakes when working with pointers
Now, let’s see some common mistakes when working with pointer in C. We make these common mistakes unconsciously especially as a beginner in programming.
// common mistakes when working with pointers in C
int x, *ptr;
ptr = x; // Error! ptr is address where x is the value
ptr = &x; // valid. both are address
*ptr = &x; // error! *ptr is value where &x is address
*ptr = x; // valid. both are value
Similarly you can work with other type of variables and pointers. You can check the same for char, float, double etc. Everything will be same for them also.
Previous page: Structure examples in C
Next page: Pointer to pointer in C
Recommended for you: