KEMBAR78
Unit 3 C Prog Notes | PDF | Pointer (Computer Programming) | Parameter (Computer Programming)
0% found this document useful (0 votes)
116 views31 pages

Unit 3 C Prog Notes

Unit III covers functions and pointers in C programming, detailing function definitions, types, advantages, and parameter passing methods including call by value and call by reference. It also explains pointers, dynamic memory allocation, and recursion, providing example programs for better understanding. The document emphasizes the importance of functions for code reusability and modularity, along with practical examples for various function types and their applications.

Uploaded by

kanimozhi
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)
116 views31 pages

Unit 3 C Prog Notes

Unit III covers functions and pointers in C programming, detailing function definitions, types, advantages, and parameter passing methods including call by value and call by reference. It also explains pointers, dynamic memory allocation, and recursion, providing example programs for better understanding. The document emphasizes the importance of functions for code reusability and modularity, along with practical examples for various function types and their applications.

Uploaded by

kanimozhi
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/ 31

Unit – III

FUNCTIONS AND POINTERS

Functions: Function definition, Types of Functions: User defined and built-in Functions,
Advantages of User Defined Functions. Parameter passing in functions: Call by value, Call
by reference, passing arrays to functions, Recursion as a different way of solving problems,
example programs to perform call by value and reference, nested functions, recursion.

Pointers: Pointer basics, pointer arithmetic, pointers to pointers, generic pointers, array of
pointers, Functions returning pointers, Dynamic memory allocation, Example program to
perform types of pointers.

Function definition
In c, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be called
multiple times to provide reusability and modularity to the C program. In other words, we can
say that the collection of functions creates a program. The function is also known as procedure
or sub routine in other programming languages.

Advantage of functions in C

There are the following advantages of C functions.

 By using functions, we can avoid rewriting same logic/code again and again in a
program.
 We can call C functions any number of times in a program and from any place in a
program.
 We can track a large C program easily when it is divided into multiple functions.
 Reusability is the main achievement of C functions.
 However, Function calling is always a overhead in a C program.

Function Aspects

There are three aspects of a C function.

Function declaration A function must be declared globally in a c program to tell the compiler
about the function name, function parameters, and return type.

Function call Function can be called from anywhere in the program. The parameter list must not
differ in function calling and function declaration. We must pass the same number of functions
as it is declared in the function declaration.
Function definition It contains the actual statements which are to be executed. It is the most
important aspect to which the control comes when the function is called. Here, we must notice
that only one value can be returned from the function.
SN C function aspects Syntax

1 Function declaration return_type function_name (argument list);

2 Function call function_name (argument_list)

return_type function_name (argument list) {function


3 Function definition
body;}

The syntax of creating function in c language is given below:

return_type function_name(data_type parameter...){


//code to be executed
}

Types of Functions

There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C header files such as
scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C programmer, so
that he/she can use it many times. It reduces the complexity of a big program and
optimizes the code.

Return Value

A C function may or may not return a value from the function. If you don't have to return
any value from the function, use void for the return type.

Let's see a simple example of C function that doesn't return any value from the function.

Example without return value:

void hello(){
printf("hello c");
}
If you want to return any value from the function, you need to use any data type such as int, long,
char, etc. The return type depends on the value to be returned from the function.

Let's see a simple example of C function that returns int value from the function.
Example with return value:

int get(){
return 10;
}
Example with return value:

int get(){
return 10;
}

Now, you need to call the function, to get the value of the function.

Different aspects of function calling

A function may or may not accept any argument. It may or may not return any value. Based on
these facts, There are four different aspects of function calls.

 function without arguments and without return value


 function without arguments and with return value
 function with arguments and without return value
 function with arguments and with return value.

Example for Function without argument and return value


Example 1
#include<stdio.h>
void printName();
void main ()
{
printf("Hello ");
printName();
}
void printName()
{
printf("Javatpoint");
}
Test it Now
Output
Hello Javatpoint
Example 2
#include<stdio.h>
void sum();
void main()
{
printf("\nGoing to calculate the sum of two numbers:");
sum();
}
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}
Test it Now
Output
Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Example for Function without argument and with return value

Example 1
#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
Test it Now
Output
Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34
Example 2: program to calculate the area of the square

#include<stdio.h>
int sum();
void main()
{
printf("Going to calculate the area of the square\n");
float area = square();
printf("The area of the square: %f\n",area);
}
int square()
{
float side;
printf("Enter the length of the side in meters: ");
scanf("%f",&side);
return side * side;
}
Test it Now

Output
Going to calculate the area of the square
Enter the length of the side in meters: 10
The area of the square: 100.000000

Example for Function with argument and without return value


`
Example 1
#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}
Test it Now

Output
Going to calculate the sum of two numbers:
Enter two numbers 10
24

The sum is 34
Example 2: program to calculate the average of five numbers.
#include<stdio.h>
void average(int, int, int, int, int);
void main()
{
int a,b,c,d,e;
printf("\nGoing to calculate the average of five numbers:");
printf("\nEnter five numbers:");
scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
average(a,b,c,d,e);
}
void average(int a, int b, int c, int d, int e)
{
float avg;
avg = (a+b+c+d+e)/5;
printf("The average of given five numbers : %f",avg);
}

Output

Going to calculate the average of five numbers:


Enter five numbers:10
20
30
40
50
The average of given five numbers : 30.000000

Example for Function with argument and with return value


Example 1
#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}

Output
Going to calculate the sum of two numbers:
Enter two numbers:10
20
The sum is : 30
Example 2: Program to check whether a number is even or odd
#include<stdio.h>
int even_odd(int);
void main()
{
int n,flag=0;
printf("\nGoing to check whether a number is even or odd");
printf("\nEnter the number: ");
scanf("%d",&n);
flag = even_odd(n);
if(flag == 0)
{
printf("\nThe number is odd");
}
else
{
printf("\nThe number is even");
}
}
int even_odd(int n)
{
if(n%2 == 0)
{
return 1;
}
else
{
return 0;
}
}

Output
Going to check whether a number is even or odd
Enter the number: 100
The number is even
Call by value in C
 In call by value method, the value of the actual parameters is copied into the formal parameters.
 In other words, we can say that the value of the variable is used in the function call in the call by value
method.
 In call by value method, we can not modify the value of the actual parameter by the formal parameter.
 In call by value, different memory is allocated for actual and formal parameters since the value of the
actual parameter is copied into the formal parameter.
 The actual parameter is the argument which is used in the function call whereas formal parameter is the
argument which is used in the function definition.
Call by reference in C
 In call by reference, the address of the variable is passed into the function call as the actual parameter.
 The value of the actual parameters can be modified by changing the formal parameters since the
address of the actual parameters is passed.
 In call by reference, the memory allocation is similar for both formal parameters and actual parameters.
All the operations in the function are performed on the value stored at the address of the actual
parameters, and the modified value gets stored at the same address.

Passing arrays to functions

In C, there are various general problems which requires passing more than one variable of the
same type to a function. For example, consider a function which sorts the 10 elements in
ascending order. Such a function requires 10 numbers to be passed as the actual parameters from
the main function. Here, instead of declaring 10 different numbers and then passing into the
function, we can declare and initialize an array and pass that into the function. This will resolve
all the complexity since the function will now work for any number of values.

As we know that the array_name contains the address of the first element. Here, we must notice
that we need to pass only the name of the array in the function which is intended to accept an
array. The array defined as the formal parameter will automatically refer to the array specified by
the array name defined as an actual parameter.

Consider the following syntax to pass an array to the function.

functionname(arrayname);//passing array
Methods to declare a function that receives an array as an argument
There are 3 ways to declare the function which is intended to receive an array as an argument.

First way:

return_type function(type arrayname[])

Second way:

return_type function(type arrayname[SIZE])


Optionally, we can define size in subscript notation [].

Third way:

return_type function(type *arrayname)

C language passing an array to function example

#include<stdio.h>
int minarray(int arr[],int size){
int min=arr[0];
int i=0;
for(i=1;i<size;i++){
if(min>arr[i]){
min=arr[i];
}
}//end of for
return min;
}//end of function

int main(){
int i=0,min=0;
int numbers[]={4,5,7,3,8,9};//declaration of array

min=minarray(numbers,6);//passing array with size


printf("minimum number is %d \n",min);
return 0;
}

Output
minimum number is 3

Recursion as a different way of solving problems

Recursion in C
Recursion is the process which comes into existence when a function calls a copy of itself to
work on a smaller problem. Any function which calls itself is called recursive function, and such
function calls are called recursive calls. Recursion involves several numbers of recursive calls.
However, it is important to impose a termination condition of recursion. Recursion code is
shorter than iterative code however it is difficult to understand.

Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be
defined in terms of similar subtasks. For Example, recursion may be applied to sorting,
searching, and traversal problems.
Generally, iterative solutions are more efficient than recursion since function call is always
overhead. Any problem that can be solved recursively, can also be solved iteratively. However,
some problems are best suited to be solved by the recursion, for example, tower of Hanoi,
Fibonacci series, factorial finding, etc.

Example programs to perform call by value and reference

In the following example, recursion is used to calculate the factorial of a number.

#include <stdio.h>
int fact (int);
int main()
{
int n,f;
printf("Enter the number whose factorial you want to calculate?");
scanf("%d",&n);
f = fact(n);
printf("factorial = %d",f);
}
int fact(int n)
{
if (n==0)
{
return 0;
}
else if ( n == 1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}

Output
Enter the number whose factorial you want to calculate?5
factorial = 120
Let's try to understand the concept of call by value in c language by the example given below:
#include<stdio.h>

void change(int num) {


printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(x);//passing value in function
printf("After function call x=%d \n", x);
return 0;
}

Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200

After function call x=100


Call by Value Example: Swapping the values of the two variables
#include <stdio.h>
void swap(int , int); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
// printing the value of a and b in main
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
// The value of actual parameters do not change by changing the formal parameters
//in call by value, a = 10, b = 20
}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a = 20, b
= 10
}

Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20
Consider the following example for the call by reference.

#include<stdio.h>
void change(int *num) {
printf("Before adding value inside function num=%d \n",*num);
(*num) += 100;
printf("After adding value inside function num=%d \n", *num);
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(&x);//passing reference in function
printf("After function call x=%d \n", x);
return 0;
}
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200
Call by reference Example: Swapping the values of the two variables
#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
// printing the value of a and b in main
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
// The values of actual parameters do change in call by reference, a = 10, b = 20
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a = 20,
b = 10
}
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10

Nested Functions:

One needs to be aware of the following points while using nested functions −

 A nested function can access all the identifiers of the containing function that precede its
definition.
 A nested function must not be called before the containing function exits.
 A nested function cannot use a goto statement to jump to a label in the containing
function.
 Nested function definitions are permitted within functions in any block, mixed with the
other declarations and statements in the block.
 If you try to call a nested function through its address after the containing function exits,
it throws an error.
 A nested function always has no linkage. Declaring one with "extern" or "static" always
produces errors.

Example
In this program, a function square() is nested inside another function myfunction(). The nested
function is declared with the auto keyword.
Open Compiler
#include <stdio.h>

#include <math.h>

double myfunction (double a, double b);

int main(){

double x = 4, y = 5;

printf("Addition of squares of %f and %f = %f", x, y, myfunction(x, y));

return 0;

}
double myfunction (double a, double b){

auto double square (double c) { return pow(c,2); }

return square (a) + square (b);

Addition of squares of 4.000000 and 5.000000 = 41.000000

Example program for recursion

Sum of Natural Numbers Using Recursion


#include <stdio.h>
int sum(int n);

int main() {
int number, result;

printf("Enter a positive integer: ");


scanf("%d", &number);

result = sum(number);

printf("sum = %d", result);


return 0;
}

int sum(int n) {
if (n != 0)
// sum() function calls itself
return n + sum(n-1);
else
return n;
}
Output
Enter a positive integer:3
sum = 6

Pointers
Pointer basics
The pointer in C language is a variable which stores the address of another variable. This
variable can be of type int, char, array, function, or any other pointer. The size of the pointer
depends on the architecture. However, in 32-bit architecture the size of a pointer is 2 byte.
Consider the following example to define a pointer which stores the address of an integer.

int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol). It is also known as
indirection pointer used to dereference a pointer.

int *a;//pointer to int


char *c;//pointer to char

Pointer Example
An example of using pointers to print the address and value is given below.

#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number;//stores the address of number variable
printf("Address of p variable is %x \n",p); // p contains the address of the number therefore printing
p gives the address of number.
printf("Value of p variable is %d \n",*p); // As we know that * is used to dereference a pointer theref
ore if we print *p, we will get the value stored at the address contained by p.
return 0;
}
Output
Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

Pointer Arithmetic in C
We can perform arithmetic operations on the pointers like addition, subtraction, etc. However, as
we know that pointer contains the address, the result of an arithmetic operation performed on the
pointer will also be a pointer if the other operand is of type integer. In pointer-from-pointer
subtraction, the result will be an integer value. Following arithmetic operations are possible on
the pointer in C language:

o Increment
o Decrement
o Addition
o Subtraction
o Comparison
Incrementing Pointer in C

If we increment a pointer by 1, the pointer will start pointing to the immediate next
location. This is somewhat different from the general arithmetic since the value of the
pointer will get increased by the size of the data type to which the pointer is pointing.

We can traverse an array by using the increment operation on a pointer which will keep pointing
to every element of the array, perform some operation on that, and update itself in a loop.

The Rule to increment the pointer is given below:

new_address= current_address + i * size_of(data type)


Test it Now

Where i is the number by which the pointer get increased.

32-bit
For 32-bit int variable, it will be incremented by 2 bytes.

64-bit
For 64-bit int variable, it will be incremented by 4 bytes.

Let's see the example of incrementing pointer variable on 64-bit architecture.

#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+1;
printf("After increment: Address of p variable is %u \n",p); // in our case, p will get incremented by
4 bytes.
return 0;
}
Output
Address of p variable is 3214864300

After increment: Address

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. If we decrement a pointer, it will start
pointing to the previous location. The formula of decrementing the pointer is given below:

new_address= current_address - i * size_of(data type)


Test it Now
32-bit
For 32-bit int variable, it will be decremented by 2 bytes.

64-bit
For 64-bit int variable, it will be decremented by 4 bytes.

Let's see the example of decrementing pointer variable on 64-bit OS.

#include <stdio.h>
void main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-1;
printf("After decrement: Address of p variable is %u \n",p); // P will now point to the immidiate prev
ious location.
}
Output

Address of p variable is 3214864300


After decrement: Address of p variable is 3214864296

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given
below:

new_address= current_address + (number * size_of(data type))


Test it Now
32-bit
For 32-bit int variable, it will add 2 * number.

64-bit
For 64-bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64-bit architecture.

#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+3; //adding 3 to pointer variable
printf("After adding 3: Address of p variable is %u \n",p);
return 0;
}
Output

Address of p variable is 3214864300


After adding 3: Address of p variable is 3214864312
As you can see, the address of p is 3214864300. But after adding 3 with p variable, it is
3214864312, i.e., 4*3=12 increment. Since we are using 64-bit architecture, it increments 12.
But if we were using 32-bit architecture, it was incrementing to 6 only, i.e., 2*3=6. As integer
value occupies 2-byte memory in 32-bit OS.

C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. Subtracting any number
from a pointer will give an address. The formula of subtracting value from the pointer variable is
given below:

new_address= current_address - (number * size_of(data type))


Test it Now
32-bit
For 32-bit int variable, it will subtract 2 * number.

64-bit
For 64-bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from the pointer variable on 64-bit architecture.

#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-3; //subtracting 3 from pointer variable
printf("After subtracting 3: Address of p variable is %u \n",p);
return 0;
}
Output
Address of p variable is 3214864300
After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from the pointer variable, it is 12 (4*3) less than the previous
address value.
However, instead of subtracting a number, we can also subtract an address from another address
(pointer). This will result in a number. It will not be a simple arithmetic operation, but it will
follow the following rule.

If two pointers are of the same type,

Address2 - Address1 = (Subtraction of two addresses)/size of data type which pointer points
Test it Now

Consider the following example to subtract one pointer from an another.

#include<stdio.h>
void main ()
{
int i = 100;
int *p = &i;
int *temp;
temp = p;
p = p + 3;
printf("Pointer Subtraction: %d - %d = %d",p, temp, p-temp);
}
Output

Pointer Subtraction: 1030585080 - 1030585068 = 3

Pointers to pointers
As we know that, a pointer is used to store the address of a variable in C. Pointer reduces the
access time of a variable. However, In C, we can also define a pointer to store the address of
another pointer. Such pointer is known as a double pointer (pointer to pointer). The first pointer
is used to store the address of a variable whereas the second pointer is used to store the address
of the first pointer. Let's understand it by the diagram given below.

The syntax of declaring a double pointer is given below.

int **p; // pointer to a pointer which is pointing to an integer.


Consider the following example.

#include<stdio.h>
void main ()
{
int a = 10;
int *p;
int **pp;
p = &a; // pointer p is pointing to the address of a
pp = &p; // pointer pp is a double pointer pointing to the address of pointer p
printf("address of a: %x\n",p); // Address of a will be printed
printf("address of p: %x\n",pp); // Address of p will be printed
printf("value stored at p: %d\n",*p); // value stoted at the address contained by p i.e. 10 will be pri
nted
printf("value stored at pp: %d\n",**pp); // value stored at the address contained by the pointer stoy
red at pp
}

Output
address of a: d26a8734
address of p: d26a8738
value stored at p: 10
value stored at pp: 10

C double pointer example

As you can see in the above figure, p2 contains the address of p (fff2), and p contains the address
of number variable (fff4).

#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
int **p2;//pointer to pointer
p=&number;//stores the address of number variable
p2=&p;
printf("Address of number variable is %x \n",&number);
printf("Address of p variable is %x \n",p);
printf("Value of *p variable is %d \n",*p);
printf("Address of p2 variable is %x \n",p2);
printf("Value of **p2 variable is %d \n",*p);
return 0;
}
Output
Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

Generic pointers
A generic pointer is a pointer variable that has void as its data type. The void pointer, or the
generic pointer, is a special type of pointer that can be used to point to variables of any data type.
It is declared like a normal pointer variable but using the void keyword as the pointer's data type.
For example,

void *ptr;

In C, since you cannot have a variable of type void, the void pointer will therefore not point to
any data and thus cannot be dereferenced. You need to type cast void pointer (generic pointer) to
another kind of pointer before using it.

Generic pointers are often used when you want a pointer to point to data of different types at
different times. For example, look at the code given below.

#include <stdio.h>
int main()
{
int x=10;
char ch = 'A';
void *gp;
gp = &x;
printf("\n Generic pointer points to the integer value = %d", *(int *) gp);
gp = &ch;
printf("\n Generic pointer now points to the character = %c", (char*) gp);
return 0;
}

Output
Generic pointer points to the integer value = 10

Generic pointer now points to the character = A

It is always recommended to avoid using void pointers unless absolutely necessary, as they
effectively allow you to avoid type checking.
Array of pointers

Just like an integer array holds a collection of integer variables, an array of pointers would hold
variables of pointer type. It means each variable in an array of pointers is a pointer that points to
another address.

The name of an array can be used as a pointer because it holds the address to the first element of
the array. If we store the address of an array in another pointer, then it is possible to manipulate
the array using pointer arithmetic.

Create an Array of Pointers

To create an array of pointers in C language, you need to declare an array of pointers in the same
way as a pointer declaration. Use the data type then an asterisk sign followed by an identifier
(array of pointers variable name) with a subscript ([]) containing the size of the array.

In an array of pointers, each element contains the pointer to a specific type.

Example of Creating an Array of Pointers

The following example demonstrates how you can create and use an array of pointers. Here, we
are declaring three integer variables and to access and use them, we are creating an array of
pointers. With the help of an array of pointers, we are printing the values of the variables.

#include <stdio.h>

int main() {
// Declaring integers
int var1 = 1;
int var2 = 2;
int var3 = 3;

// Declaring an array of pointers to integers


int *ptr[3];

// Initializing each element of


// array of pointers with the addresses of
// integer variables
ptr[0] = &var1;
ptr[1] = &var2;
ptr[2] = &var3;

// Accessing values
for (int i = 0; i < 3; i++) {
printf("Value at ptr[%d] = %d\n", i, *ptr[i]);
}
return 0;
}

Output

When the above code is compiled and executed, it produces the following result −

Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200

Functions returning pointers

Although it may appear difficult at first glance, we may declare the appropriate function using a
sequence of deconstructed statements.

1. We require a function with the argument int *.

function(int *)

2. A function that takes an int * argument and returns a pointer to

(*function(int *))

3. a function with the argument int * that returns a pointer to a 4-array.

(*function(int *))

[4]

4. a function with the argument int *, which returns a pointer to an array of four integer pointers

int *(*function(int *))[4];

How can we be certain that the preceding declaration is completely right? The following
program can validate our declaration.

Code(syntax):
#include<stdio.h>

#define SIZE_OF_ARRAY (4)

typedef int *(*p_array_t)[SIZE_OF_ARRAY];


int *(*function(int *arg))[4];

p_array_t function(int *arg)


{
static int *arr[SIZE_OF_ARRAY] = {NULL};

p_array_t pRet = &arr;


return pRet;
}
int main()
{
}
The macro SIZE_OF_ARRAY serves to represent array size symbolically. The type definition of
p_array_t is "pointer to an array of four integers." If our declaration is incorrect, the program
stops working at the definition of the 'function.'

Part 2: The aim is to write a function with the provided array that returns a pointer to an array of
integer function pointers.

For that, we'll enter the two values, execute a function that compares them, then use a function
pointer to get the memory location of the larger value and output the result. Functions are made
more flexible and abstract by using the function pointer to provide addresses of various functions
at various times. Therefore, by offering a straightforward method to choose a function to execute
based on run-time information, function pointers can be utilised to simplify code.

Illustration of the big function ()

The function big() is called by the application and receives two integer values by reference. It
compares the two values and returns the memory address of the larger number. Big() has an
integer return value that can be either a non-zero or a zero number.

For instance,

Input ? 8 14
Output ? Bigger value is 14
Input ?5 9
Output? Bigger value is 9

Analysis: After comparing the two integer values that we had, the pointer will return the
memory location with the biggest value.

A method that could be used

Consider the integer pointer int *c.


o The two integer variables should be initialised.
o We will enter the two values.
o Comparing the two values provided.
o Pointer *c finally returns the address of a larger value.
Algorithm

Start
STEP 1-> Pass the argument to the function after creating it.
Int *big(int &, int &)
END
STEP 2-: calling the main() function to initialise the pointer *c and enter and output two values.
int p, q, *c
call c= big(p,q)
print c
END
STEP 3-
> Pointer c returns the memory address of the larger value after comparing the two integer values giv
en to it.
Comparing
If(a>b)
return(&a)
else
return(&b)
END
STOP

#include<iostream.h>
int *big(int&, int&);
int main( ){
int p, q, *c;
c= big(3, 9);
cout<<"The bigger value is"<<*c;
";
return 0;
}
int *big(int&a, int&b){
if(a>b)
return(&a);
else
return(&b);
}
Output:

Running the above mentioned code will result in the output shown below.
The bigger value is 9
Dynamic memory allocation in C
The concept of dynamic memory allocation in c language enables the C programmer to
allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions
of stdlib.h header file.

1. malloc()
2. calloc()
3. realloc()
4. free()

Before learning above functions, let's understand the difference between static memory
allocation and dynamic memory allocation.

malloc() function in C

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

ptr=(cast-type*)malloc(byte-size)
Test it Now

Let's see the example of malloc() function.

#include<stdio.h>
#include<stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
Output
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

calloc() function in C

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

1. ptr=(cast-type*)calloc(number, byte-size)
Test it Now

Let's see the example of calloc() function.

#include<stdio.h>
#include<stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
Output
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc()
function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

ptr=realloc(ptr, new-size)
Test it Now

free() function in C

The memory occupied by malloc() or calloc() functions must be released by calling free()
function. Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

free(ptr)

Types of Pointers in C

Pointers in C can be classified into many different types based on the parameter on which we are
defining their types. If we consider the type of variable stored in the memory location pointed by
the pointer, then the pointers can be classified into the following types:

1. Integer Pointers

As the name suggests, these are the pointers that point to the integer values.

Syntax

int *ptr;

These pointers are pronounced as Pointer to Integer.

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. We can create a pointer to an array using the
given syntax.

Syntax

char *ptr = &array_name;

Pointer to Arrays exhibits some interesting properties which we discussed later in this article.

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.

Syntax

struct struct_name *ptr;

In C, structure pointers are used in data structures such as linked lists, trees, etc.

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. Let’s consider a function
prototype – int func (int, char), the function pointer for this function will be

Syntax

int (*ptr)(int, char);

Note: The syntax of the function pointers changes according to the function prototype.

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.

Syntax

datatype ** pointer_name;
Dereferencing Double Pointer

*pointer_name; // get the address stored in the inner level pointer


**pointer_name; // get the value pointed by inner level pointer

Note: 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.

Syntax

data_type *pointer_name = NULL;


or
pointer_name = NULL

It is said to be good practice to assign NULL to the pointers currently not in use.

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.

Syntax

void * pointer_name;

One of the main properties of void pointers is that they cannot be dereferenced.

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
is updated using wild pointers, they could cause data abort or data corruption.

Example

int *ptr;
char *str;
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.

Syntax

data_type * const pointer_name;

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.

Syntax

const data_type * pointer_name;

You might also like