Pointers
Pointers
• Instead of holding a direct value, it holds the address where the value is stored in
memory. There are 2 important operators that we will use in pointers concepts
i.e.
// taking an integer variable
int number = 100;
// pointer variable ptr that stores the address of variable m
int *p = &number;
•Dereferencing operator(*) used to declare pointer variable and access the value
stored in the address.
To declare a pointer, we use the (*) dereference operator before its name. In
pointer declaration, we only declare the pointer but do not initialize it.
int * ptr;
Pointer Initialization
Pointer initialization is the process where we assign some initial value to the
pointer variable. We use the (&) addressof operator to get the memory
address of a variable and then store it in the pointer variable.
ptr = &a;
Note: We can also declare and initialize the pointer in a single step. This is
called pointer definition.
Pointer Dereferencing
int main() {
// An integer variable
int a = 10;
return 0;
}
Pointer to Pointer (Double Pointer)
In C, double pointers are those pointers which stores the address of another pointer.
The first pointer is used to store the address of the variable, and the second pointer is
used to store the address of the first pointer. That is why they are also known as
a pointer to pointer.
The syntax to use double pointer can be divided into three parts:
Declaration
A double pointer can be declared similar to a single pointer. The difference is we have
to place an additional ‘*’ before the name of the pointer.
type **name;
Above is the declaration of the double pointer with some name to the given type.
Initialization
The double pointer stores the address of another pointer to the same type.
Deferencing
To access the value pointed by double pointer, we have to use the deference operator *
two times.
#include <stdio.h>
int main() {
// A variable
int var = 10;
// Pointer to int
int *ptr1 = &var;
type(*ptr)[size];
where,
int (*ptr)[10];
Here ptr is pointer that points to an array of 10 integers. Since subscript have higher
precedence than indirection, it is necessary to enclose the indirection operator and pointer
name inside parentheses.
Output
Call By Value in C
In call by value method of parameter passing, the values of actual parameters are copied to
the function’s formal parameters.
•There are two copies of parameters stored in different memory locations.
•One is the original copy and the other is the function copy.
•Any changes made inside functions are not reflected in the actual parameters of the caller.
Output
Inside swapx: x = 20 y =
10
Inside main: a = 10 b = 20
Call by Reference in C
•Any changes made inside the function are actually reflected in the actual parameters
of the caller.
Output
Inside swapx: x = 20 y = 10
Inside main: a = 20 b = 10