Pointers
Pointers
Pointers
What is a Pointer in C?
• A pointer is defined as a derived data type that
can store the address of other C variables or a
memory location. We can access and manipulate
the data stored in that memory location using
pointers.
• As the pointers in C store the memory addresses,
their size is independent of the type of data they
are pointing to.
• This size of pointers in C only depends on the
system architecture.
Syntax of C Pointers
• The syntax of pointers is similar to the variable
declaration in C, but we use the ( * ) dereferencing
operator in the pointer declaration.
datatype * ptr;
where
• ptr is the name of the pointer.
• datatype is the type of data it is pointing to.
• The above syntax is used to define a pointer to a
variable. We can also define pointers to functions,
structures, etc.
How to Use Pointers?
The use of pointers in C can be divided into three steps:
• Pointer Declaration
• Pointer Initialization
• Pointer Dereferencing
1. Pointer Declaration
In pointer declaration, we only declare the pointer but do not
initialize it. To declare a pointer, we use the ( * ) dereference
operator before its name.
• Example
int *ptr;
• We can also declare and initialize the pointer in a single step. This method
is called pointer definition as the pointer is declared and initialized at the
same time.
Example
int *ptr = &var;
Note: Function call is neccessary to bring the program control to the function definition. If
not called, the function statements will not be executed.
Create a Function
• To create (often referred to as declare) your own function,
specify the name of the function, followed by
parentheses () and curly brackets {}:
The value of each variable in the calling function The address of actual variables in the calling
is copied into corresponding dummy variables of function is copied into the dummy variables of
the called function. the called function.
The changes made to the dummy variables in the Using addresses we would have access to the
called function have no effect on the values of actual variables and hence we would be able to
actual variables in the calling function. manipulate them.
In call-by-values, we cannot alter the values of In call by reference, we can alter the values of
actual variables through function calls. variables through function calls.
Values of variables are passed by the Simple Pointer variables are necessary to define to store
technique. the address values of variables.
This method is preferred when we have to pass This method is preferred when we have to pass a
some small values that should not change. large amount of data to the function.
Recursion
• A function that calls itself is known as a recursive function. And, this
technique is known as recursion.
• The recursion continues until some condition is met to prevent it.
• To prevent infinite recursion, if...else statement (or similar approach) can
be used where one branch makes the recursive call, and other doesn't.