0% found this document useful (0 votes)
7 views

unit-3 computer programming

This document provides a comprehensive overview of pointers and functions in C programming. It covers the definition and types of pointers, pointer operators, pointer arithmetic, and the concept of functions including user-defined, library, and recursive functions. Additionally, it explains the passing of parameters by value and by reference, as well as the use of function pointers.

Uploaded by

saransh8998
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

unit-3 computer programming

This document provides a comprehensive overview of pointers and functions in C programming. It covers the definition and types of pointers, pointer operators, pointer arithmetic, and the concept of functions including user-defined, library, and recursive functions. Additionally, it explains the passing of parameters by value and by reference, as well as the use of function pointers.

Uploaded by

saransh8998
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

UNIT-3

POINTERS AND FUNCTIONS

A pointer is a variable that stores the memory address of another variable. 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.
 Dereferencing operator (*) used to declare pointer variable and access the value stored in the
address.
 Address operator (&) used to returns the address of a variable or to access the address of a variable
to a pointer.
Example 1:
#include <stdio.h>

int main()
{

// taking an integer variable


int m = 100;

// pointer variable ptr that stores


// the address of variable m
int *ptr = &m;

// printing the value of variable m


printf("The Value of Variable m is: %d\n", m);

// printing the memory address of variable m


// in hexadecimal format
printf("The Memory Address of Variable m is: %p\n", &m);

// printing the value of ptr i.e.


// printing the memory address of variable m
// in hexadecimal format using pointer variable
printf("The Memory Address of Variable m is using ptr: %p\n", ptr);

return 0;
}

Notes:
 %p format specifier is used to print the address stored in pointer variables.
 Printing a pointer with %d format specifier may result in a warning or undefined behavior because
the size of a pointer (usually 4 or 8 bytes) may not match that of an integer.
 The memory address format will always be in hexadecimal format (starting with 0x).
 C does not use the term “reference” explicitly (unlike C++), “referencing” in C usually refers to
obtaining the address of a variable using the address operator (&).
 Pointers are essential for dynamic memory allocation, providing control over memory usage with
functions like malloc, calloc, and free.
Pointer Declaration
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.
Pointer Initialization
Pointer initialization is the process where we assign some initial value to the pointer variable. We use
the (&) address of operator to get the memory address of a variable and then store it in the pointer
variable.
Note: We can also declare and initialize the pointer in a single step. This is called pointer definition.
C. 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.

#include <stdio.h>

int main() {

// an integer variable
int a = 10;

// create a pointer to integer (declaration)


int * ptr;

// Store the address of an inside pointer (initialization)


ptr = &a;

// Print the content of ptr


printf ("ptr = %p\n", ptr);

// Get the value pointed by ptr (dereferencing)


printf("*ptr = %d", *ptr);

return 0;
}
Types of Pointers in C
Pointers in C can be classified into many different types depending on the data it is pointing to:
1. Integer Pointers
As the name suggests, these are the pointers that point to the integer values. These pointers are
pronounced as Pointer to Integer. Similarly, a pointer can point to any primitive data type and is named
accordingly.
Similarly, a pointer can point to any primitive data type. It can point also point to derived data types such
as arrays and user-defined data types such as structures.
2. Array Pointer
Pointers and Array are closely related to each other. Even the array name is the pointer to its first element.
They are also known as Pointer to Arrays.
3. Structure Pointer
The pointer pointing to the structure type is called Structure Pointer or Pointer to Structure. It can be
declared in the same way as we declare the other primitive data types.
4. Function Pointers
Function pointers point to the functions. They are different from the rest of the pointers in the sense that
instead of pointing to the data, they point to the code.
5. Double Pointers
In C language, we can define a pointer that stores the memory address of another pointer. Such pointers
are called double-pointers or pointers-to-pointer. Instead of pointing to a data value, they point to another
pointer.
In C, we can create multi-level pointers with any number of levels such as – ***ptr3, ****ptr4,
******ptr5 and so on.
6. NULL Pointer
The Null Pointers are those pointers that do not point to any memory location. They can be created by
assigning a NULL value to the pointer. A pointer of any type can be assigned the NULL value.
7. Void Pointer
The Void pointers in C are the pointers of type void. It means that they do not have any associated data
type. They are also called generic pointers as they can point to any type and can be typecasted to any
type.
8. Wild Pointers
The Wild Pointers are pointers that have not been initialized with something yet. These types of C-
pointers can cause problems in our programs and can eventually cause them to crash. If values are updated
using wild pointers, they could cause data abort or data corruption.
9. Constant Pointers
In constant pointers, the memory address stored inside the pointer is constant and cannot be modified
once it is defined. It will always point to the same memory address.
10. Pointer to Constant
The pointers pointing to a constant value that cannot be modified are called pointers to a constant. Here
we can only access the data pointed by the pointer, but cannot modify it. Although, we can change the
address stored in the pointer to constant.
Other Types of Pointers in C
There are also the following types of pointers available to use in C apart from those specified above:
 Far pointer: A far pointer is typically 32-bit that can access memory outside the current segment.
 Dangling pointer: A pointer pointing to a memory location that has been deleted (or freed) is called
a dangling pointer.
 Huge pointer: A huge pointer is 32-bit long containing segment address and offset address.
 Complex pointer: Pointers with multiple levels of indirection.
 Near pointer: Near pointer is used to store 16-bit addresses means within the current segment on a
16-bit machine.
 Normalized pointer: It is a 32-bit pointer, which has as much of its value in the segment register as
possible.
 File Pointer: The pointer to a FILE data type is called a stream pointer or a file pointer.

Chain of pointers is when there are multiple levels of pointers. Simplifying, a pointer points to address
of a variable, double-pointer points to a variable and so on. This is called multiple indirections.
Syntax:

// level-1 pointer declaration


Datatype *pointer;

// level-2 pointer declaration


datatype **pointer;

// level-3 pointer declaration


datatype ***pointer;
.
.
and so on
The level of the pointer depends on how many asterisks the pointer variable is preceded with at the time
of declaration.
Declaration:

int *pointer_1;
int **pointer_2;
int ***pointer_3;
.
.
and so on
Level of pointers or say chain can go up to N level depending upon the memory size. If you want to
create a pointer of level-5, you need to precede the pointer variable name by 5 asterisks(*) at the time of
declaration.
Initialization:

// initializing level-1 pointer


// with address of variable 'var'
pointer_1 = &var;
// initializing level-2 pointer
// with address of level-1 pointer
pointer_2 = &pointer_1;

// initializing level-3 pointer


// with address of level-2 pointer
pointer_3 = &pointer_2;
.
.
and so on

Pointers Operators:
There are two types of pointer operators. They are
1.Address operator (&)
2. Indirection operator (*)

Address Operator:
It is used to get the address of the given variable. Consider the following,
Example:
int a = 10, *ptr;
ptr = &a;
Here, &a gives us the address of the variable a and the same is address to pointer variable ptr. Address
operator is also known as reference operator.
Indirection operator:
It is used to get the value stored in an address. Consider the following,
Example:
int a = 10, b, *ptr;
ptr = &a; // referencing(&a)
b = *ptr; // dereferencing(*ptr)

Pointer Arithmetic: Pointer Arithmetic is the set of valid arithmetic operations that can be performed on
pointers. The pointer variables store the memory address of another variable. It doesn’t store any value.
These operations are:
1. Increment/Decrement of a Pointer
2. Addition of integer to a pointer
3. Subtraction of integer to a pointer
4. Subtracting two pointers of the same type
5. Comparison of pointers

Introduction to Function: A function in C is a set of statements that when called perform some specific
tasks. It is the basic building block of a C program that provides modularity and code reusability. The
programming statements of a function are enclosed within { } braces, having certain meanings and
performing certain operations. They are also called subroutines or procedures in other languages.
The syntax of function can be divided into 3 aspects:
Function Declaration. Syntax
return_type name_of_the_function (parameter_1, parameter_2);
Example
int sum(int a, int b); // Function declaration with parameter names
int sum(int , int); // Function declaration without parameter names

Function Definition. Syntax: return_type function_name (para1_type para1_name, para2_type


para2_name)
{
// body of the function
}
3. Function Calls.

Need of C function: Functions are crucial in C programming because they enable code reusability,
modularity, and readability, making large projects easier to manage and debug. They allow breaking down
complex tasks into smaller, manageable units, which promotes better code organization and reduces
redundancy.

User defined function:


 Functions that can be created by the programmer and used multiple times
 Can reduce the complexity of large programs and optimize code.
Ex: #include <stdio.h>

// Function that takes two parameters


// a and b as inputs and returns
// their sum
int sum (int a, int b)
{
return a + b;
}

// Driver code
int main ()
{
// Calling sum function and
// storing its value in add variable
int add = sum (10, 30);

printf ("Sum is: %d", add);


return 0;
}

Library functions:
 Inbuilt functions in C that are declared in the header files
 Examples include floor(), ceil(), outs(), gets(), printf(), and scanf().
Ex: #include <math.h>
#include <stdio.h>

// Driver code
int main ()
{
double Number;
Number = 49;

// computing the square root with


// the help of predefined C
// library function
double squareRoot = sqrt(Number);

printf("The Square root of %.2lf = %.2lf",


Number, squareRoot);
return 0;
}

Recursive functions
 A special type of function that can call itself
 Can be a useful tool for solving certain types of problems.

We can pass arguments to the C function in two ways:


1. Pass by Value
2. Pass by Reference

1. Pass by Value
Parameter passing in this method copies values from actual parameters into formal function parameters.
#include <stdio.h>

void swap (int var1, int var2)


{
int temp = var1;
var1 = var2;
var2 = temp;
}

// Driver code
int main ()
{
int var1 = 3, var2 = 2;
printf("Before swap Value of var1 and var2 is: %d, %d\n",
( var1, var2);
swap(var1, var2);
printf("After swap Value of var1 and var2 is: %d, %d",
var1, var2);
return 0;
}

Output
Before swap Value of var1 and var2 is: 3, 2
After swap Value of var1 and var2 is: 3, 2

Pass by Reference
The caller’s actual parameters and the function’s actual parameters refer to the same locations, so any
changes made inside the function are reflected in the caller’s actual parameters.
Example:
// C program to show use of
// call by Reference
#include <stdio.h>

void swap(int *var1, int *var2)


{
int temp = *var1;
*var1 = *var2;
*var2 = temp;
}
// Driver code
int main()
{
int var1 = 3, var2 = 2;
printf("Before swap Value of var1 and var2 is: %d, %d\n",
var1, var2);
swap(&var1, &var2);
printf("After swap Value of var1 and var2 is: %d, %d",
var1, var2);
return 0;
}

Output
Before swap Value of var1 and var2 is: 3, 2
After swap Value of var1 and var2 is: 2, 3

Prototype of function: In C, a function prototype, also called a function declaration, specifies a function's
name, return type, and the number and types of its parameters, without providing the actual
implementation (the function body).
Function prototypes act as a "blueprint" for the compiler, informing it about the function before
it's actually used in the code.
Syntax:
A function prototype typically looks like this: return_type function name (parameter_type1
parameter_name1, parameter_type2 parameter_name2, ...).
 return_type: The data type of the value the function will return (e.g., int, float, void).
 function _name: The name of the function.
 parameter_type: The data type of each parameter the function takes (e.g., int, char, float).
 parameter_name: The name of each parameter (optional in the prototype, but good practice to include).
// Function prototype
int add(int a, int b);

int main() {
int result = add(5, 3); // Call the function
printf("Result: %d\n", result);
return 0;
}

// Function definition (can be placed after main)


int add(int a, int b) {
return a + b;
}
Recursion function: Recursion is the technique of making a function call itself. This technique provides a
way to break complicated problems down into simple problems which are easier to solve.

Ex. int sum(int k);

int main() {
int result = sum(10);
printf("%d", result);
return 0;
}

int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else

{
return 0;
}
}

Pointers with function: Function Pointers point to code like normal pointers.

In Functions Pointers, function’s name can be used to get function’s address.

A function can also be passed as an arguments and can be returned from a function.

Declaration

function_return_type(*Pointer_name)(function argument list)

Example

#include<stdio.h>
int subtraction (int a, int b) {
return a-b;
}
int main() {
int (*fp) (int, int)=subtraction;
//Calling function using function pointer
int result = fp(5, 4);
printf(" Using function pointer we get the result: %d",result);
return 0;
}

You might also like