Pointers

Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

UNIT – III

Pointers: Definition and declaration and initialization of pointers.


Accessing values using pointers. Accessing array elements using
pointers.
Functions: Definition and declaration. Built-in functions and User-
defined functions. Categories of functions with example. Pointers
as function arguments, array as function argument, Call-by-value
and call-by-reference. Recursion.
C 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;

• The pointer declared here will point to some random memory


address as it is not initialized. Such pointers are called wild
pointers.
2. Pointer Initialization
• Pointer initialization is the process where we assign some initial value to
the pointer variable. We generally use the ( & ) addressof operator to get
the memory address of a variable and then store it in the pointer variable.
Example
int var = 10;
int * ptr;
ptr = &var;

• 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: It is recommended that the pointers should always be initialized to


some value before starting using it. Otherwise, it may lead to number of
errors.
3. Pointer Dereferencing
• Dereferencing a pointer is the process of accessing the value
stored in the memory address specified in the pointer. We use
the same ( * ) dereferencing operator that we used in the
pointer declaration.
Dereference
• In the previous example , we used the pointer variable to get the memory
address of a variable (used together with the & reference operator).
• You can also get the value of the variable the pointer points to, by using
the * operator (the dereference operator):
C Pointers and Arrays
Pointers & Arrays
• You can also use pointers to access arrays.
• Consider the following array of integers:
Example
int myNumbers[4] = {25, 50, 75, 100};
• You learned from the arrays chapter that you can loop through the array elements
with a for loop:
• Instead of printing the value of each array element, let's
print the memory address of each array element:

• Note that the last number of each of the elements'


memory address is different, with an addition of 4.
• It is because the size of an int type is typically 4 bytes,
remember:
So from the "memory address example" above, you can see that the compiler
reserves 4 bytes of memory for each array element, which means that the
entire array takes up 16 bytes (4 * 4) of memory storage:
How Are Pointers Related to Arrays
• In C, the name of an array, is actually a pointer to the first element of the array.
• Confused? Let's try to understand this better, and use our "memory address
example" above again.
• The memory address of the first element is the same as the name of the array:
• This basically means that we can work with arrays through
pointers!
• How? Since myNumbers is a pointer to the first element in
myNumbers, you can use the * operator to access it:
• To access the rest of the elements in myNumbers, you can
increment the pointer/array (+1, +2, etc):
• Or loop through it:
It is also possible to change the value
of array elements with pointers:
Printing the one dimensional array
elements via pointers
Accessing the elements of the two dimensional array
via pointer

In the following code we are printing the


content of the num array using for loop
and by incrementing the value of ptr.

The two dimensional array num will be


saved as a continuous block
in the memory.
So, if we increment the value of ptr by 1
we will move to the next block in the
allocated memory.
Pointer Arithmetics in C

The C pointer arithmetic operations are slightly


different from the ones that we generally use for
mathematical calculations.

These operations are:


➢ Increment/Decrement of a Pointer
➢ Addition of integer to a pointer
➢ Subtraction of integer to a pointer
➢ Subtracting two pointers of the same type
➢ Comparison of pointers
Advantages of Pointers are :-
• Pointer provide direct access to the memory.
• Pointer provide a way to returns more than one value to the
functions.
• Pointers provides an alternate way to access array elements.
• Pointers reduces the storage space and complexity of the program.
• Pointer reduces the execution of the program.

Disadvantages of Pointers are :-


• Pointer are slower than normal variables.
• Uninitialized pointer might cause segmentation fault.
• Dynamically allocated block needs to be freed explicity. Otherwise,
it would lead to memory task.
• If pointer bugs are updated with incorrect values, it migh lead to
memory corruption.
• Basically, pointer bugs are difficult to handle. So, use pointer
effectively and correctly.
C Functions

• A function is a block of code which only runs


when it is called.
• A function in C is a set of statements that when
called perform some specific task.
• You can pass data, known as parameters, into a
function.
• Functions are used to perform certain actions,
and they are important for reusing code: Define
the code once, and use it many times.
• They are also called subroutines or procedures in
other languages.
Predefined Functions

• You already know what a function is. You have


been using it the whole time while writing
programs.
• For example, main() is a function, which is
used to execute code, and printf() is a
function; used to output/print text to the
screen:
Syntax of Functions in C
The syntax of function can be divided into 3
aspects:
• Function Declaration
• Function Definition
• Function Calls
Function Declarations
• In a function declaration, we must provide the function name, its return
type, and the number and type of its parameters. A function declaration
tells the compiler that there is a function with the given name defined
Syntax

return_type name_of_the_function (parameter_1, parameter_2);

• The parameter name is not mandatory while declaring functions. We can


also declare the function without using the name of the data variables.
Example
• int sum(int a, int b);
• int sum(int , int);

Note: A function in C must always be declared


globally before calling it.
Function Definition
• The function definition consists of actual statements which
are executed when the function is called (i.e. when the
program control comes to the function).
C Function Declaration and Definition

➢ For code optimization, it is recommended to separate the declaration and


the definition of the function.
➢ You will often see C programs that have function declaration above main(), and function
definition below main().
➢ This will make the code better organized and easier to read:
Function Call
• A function call is a statement that instructs the compiler to execute the
function. We use the function name and parameters in the function call.

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 {}:

• myFunction() is the name of the function


• void means that the function does not have a return value.
You will learn more about return values later in the next
topics
• Inside the function (the body), add code that defines what
the function should do
Call a Function
• Declared functions are not executed immediately. They are "saved for
later use", and will be executed when they are called.
• To call a function, write the function's name followed by two
parentheses () and a semicolon ;
• In the following example, myFunction() is used to print a text (the action),
when it is called:
A function can be called multiple
times:
C Function Parameters
Parameters and Arguments
• Information can be passed to functions as a parameter. Parameters act as variables inside the
function.
• Parameters are specified after the function name, inside the parentheses. You can add as
many parameters as you want, just separate them with a comma:
• A parameter is a variable that we use in a function definition. (Formal parameters)
• An argument is the actual data that we pass to the function parameter.(Actual Paramaters)

The following function that takes a string of


characters with name as parameter. When the
function is called, we pass along a name, which
is used inside the function to print "Hello" and
the name of each person.
Multiple Parameters
• Inside the function, you can add as many parameters as you
want:
Pass Arrays as Function Parameters
• You can also pass arrays to a function:
Return Values
• The void keyword, used in the previous examples, indicates that the
function should not return a value.
• If you want the function to return a value, you can use a data type (such
as int or float, etc.) instead of void, and use the return keyword inside the
function:

This example returns the sum of a function


with two parameters:
• You can also store the result in a variable:
Function categories

• There are 4 types of functions:


1. Functions with arguments and return values
2. Functions with arguments and without
return values
3. Functions without arguments and with
return values
4. Functions without arguments and without
return values
Pointers as function arguments
• Passing the pointers to the function means the memory location of the variables is passed to
the parameters in the function, and then the operations are performed.
• The function definition accepts these addresses using pointers, addresses are stored using
pointers.
Arguments Passing without pointer
• When we pass arguments without pointers the changes made by the function would be done
to the local variables of the function.
Arguments Passing with pointers
• A pointer to a function is passed in this example. As an argument, a pointer is
passed instead of a variable and its address is passed instead of its value.
• As a result, any change made by the function using the pointer is permanently
stored at the address of the passed variable.
• In C, this is referred to as call by reference.
Difference between the Call by Value and Call by Reference
Call By Value Call By Reference
While calling a function, instead of passing the
While calling a function, we pass the values of
values of variables, we pass the address of
variables to it. Such functions are known as “Call
variables(location of variables) to the function
By Values”.
known as “Call By References.

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.

Advantages and Disadvantages of Recursion

Recursion makes program elegant. However, if


performance is vital, use loops instead as
recursion is usually much slower.

That being said, recursion is an important


concept. It is frequently used in data structure
and algorithms.

For example, it is common to use recursion in


problems such as tree traversal.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy