- 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- Unary operator &(ampersand) to returns the
address of that variable
- 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- Declare the pointer variable
- Assign the address of the variable to a pointer variable
- Access the value
Sample Program:
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 :
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.
Program :
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.
Excellent explanation
ReplyDelete