Pointers in C Programming



  • Before going to start pointers. Let’s recall the concepts of variables, Variable is a memory location and every memory location has an address that can be accesses through the ampersand(&) operator.
  • Let us consider an example for a clear understanding of variables and their addresses.

    Program:

   Output:


Pointers:

A pointer is a variable that stores the address of another variable. To use the function of pointers in C language we must understand the two unary operators
  1. Unary operator &(ampersand) to returns the address of that variable
  1.  Unary operator *(asterisk) is used for two things-Used to declare the pointer variable and used to access the value stored in the variable

Declaration of pointer:

Type *var_name;
Here type is pointers base type i.e it must be valid c data type and var_name is the name of the pointer variable. *(Asterisk) is used to declare the pointer variable. Here is some of the various pointer variable declarations
int *ip;
double *dp;
float *fp;
char *cp;
There are mainly three steps involved to use the pointers effectively
  1. Declare the pointer variable
  2. Assign the address of the variable to a pointer variable
  3. Access the value

Sample Program:


Output:


Pointers to array:-

int shsArray[10];
int *ptr = &shsArray;

In the below example array pointer ptr stores the address of the shsArray

Example :

Output :



Null Pointer:-

  • If the pointer is declared as NULL then it is called a null pointer. If the programmer has no value of pointer at the time of declaration then the pointer is assigned by a NULL value. It gives a better approach to solve problems.
Program :


Output :


Advantages of the pointers:-
  • Pointers reduce the code.
  • Pointers increase the performance of the code.
  • Pointers are used in arrays, structures, and functions.
  • Pointers are used to return the multiple values from the functions.
  • Dynamic memory allocation is possible in pointers using malloc() and calloc() functions.

Here is an example to clearly understand the working of the pointers in a c programming language. The problem statement is swapping of the two numbers using pointers

Program :


Output :



Note: More examples will be covered in Problems on C page
Similarly you can also learn the structures, arrays and unions concepts in C programming Language.

If you have any doubts or you want us to create some more concepts or if you can't solve any problems please give it in the form of your comments.


If you like the content we had given and understood it well then give your valuable rating for this page and comment your experience in the comment Box for improvement.




 


Categories:

1 comment: