Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
19 views44 pages

Unit 3

The document covers key concepts in C programming related to functions, pointers, and memory management. It explains call by value and call by reference, recursion, pointer arithmetic, and dynamic memory allocation using functions like malloc, calloc, and realloc. Additionally, it discusses function pointers and their properties, as well as arrays of pointers and their applications.

Uploaded by

infinityinfo122
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)
19 views44 pages

Unit 3

The document covers key concepts in C programming related to functions, pointers, and memory management. It explains call by value and call by reference, recursion, pointer arithmetic, and dynamic memory allocation using functions like malloc, calloc, and realloc. Additionally, it discusses function pointers and their properties, as well as arrays of pointers and their applications.

Uploaded by

infinityinfo122
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/ 44

UNIT-3

Functions & Pointers


Call by Value
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.
void swap(int x, int y) {
int t;
t = x;
x = y;
y = t;
printf("Inside swapx: x = %d y = %d\n", x, y);
}

int main() {
int a = 10, b = 20;

// Pass by Values
swap(a, b);
printf("Inside main: a = %d b = %d", a, b);
return 0;
}
Call by Reference
• In call by reference method of parameter
passing, the address of the actual parameters is
passed to the function as the formal
parameters.
• Both the actual and formal parameters refer to
the same locations.
• Any changes made inside the function are
actually reflected in the actual parameters of
the caller.
void swap(int* x, int* y) {
int t;
t = *x;
*x = *y;
*y = t;
printf("Inside swapx: x = %d y = %d\n", *x, *y);
}

int main() {
int a = 10, b = 20;

// Pass by reference
swap(&a, &b);

printf("Inside main: a = %d b = %d", a, b);


return 0;
}
Recursion
• A function that calls itself is called Recursive
Function
// C program to find factorial of given number
#include <stdio.h>
int factorial(int n)
{
if (n == 0)
return 1;
return n * factorial(n - 1);
}
int main()
{
int num = 5;
printf("Factorial of %d is %d", num, factorial(num));
return 0;
}
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
• A pointer is a variable that stores the memory
address of another variable as its value.
• 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.
int myAge = 43;
int* ptr = &myAge;

printf("%d\n", myAge);

printf("%p\n", &myAge);

printf("%p\n", ptr);
Dereference
• Get the value of the variable the pointer points to,
by using the * operator (the dereference operator)
• int myAge = 43;
int* ptr = &myAge;

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

printf("%d\n", *ptr); // Dereference


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 (&) addressof
operator to get the memory address of a
variable and then store it in the pointer
variable.
Types of Pointers in C
• Integer Pointers
• Array Pointer
• Structure Pointer
• Function Pointers
• Double Pointers
• NULL Pointer
• Void Pointer
Pointer Arithmetic
• The Pointer Arithmetic refers to the legal or valid
arithmetic operations that can be performed on
a pointer.
• Increment/Decrement by 1
• Addition/Subtraction of Integer
• Subtracting Two Pointers of Same Type
• Comparing/Assigning Two Pointers of Same Type
• Comparing/Assigning with NULL
Increment/Decrement of a Pointer
• When a pointer is incremented, it actually
increments by the number equal to the size of
the data type for which it is a pointer.
• If an integer pointer that stores address
1000 is incremented, then it will increment by
4(size of an int), and the new address will
point to 1004.
int main()
{
int a = 22;
int *p = &a;
printf("p = %u\n", p); // p = 6422288
p++;
printf("p++ = %u\n", p); //p++ = 6422292 +4 // 4 bytes
p--;
printf("p-- = %u\n", p); //p-- = 6422288 -4 // restored to original value

float b = 22.22;
float *q = &b;
printf("q = %u\n", q); //q = 6422284
q++;
printf("q++ = %u\n", q); //q++ = 6422288 +4 // 4 bytes
q--;
printf("q-- = %u\n", q); //q-- = 6422284 -4 // restored to original value

char c = 'a';
char *r = &c;
printf("r = %u\n", r); //r = 6422283
r++;
printf("r++ = %u\n", r); //r++ = 6422284 +1 // 1 byte
r--;
printf("r-- = %u\n", r); //r-- = 6422283 -1 // restored to original value

return 0;
}
Addition of Integer to Pointer
• When a pointer is added with an integer
value, the value is first multiplied by the size of
the data type and then added to the pointer.
• ptr = ptr + 5
• ptr = 1000 + sizeof(int) * 5 = 1020.
Subtraction of Integer to Pointer
• When a pointer is subtracted with an integer
value, the value is first multiplied by the size of
the data type and then subtracted from the
pointer similar to addition.
• ptr = 1000 – sizeof(int) * 5 = 980.
Subtraction of Two Pointers
• The subtraction of two pointers is possible only when they
have the same data type.
• The result is generated by calculating the difference
between the addresses of the two pointers and calculating
how many bytes of data it is according to the pointer data
type.
• Two integer pointers
say ptr1(address:1000) and ptr2(address:1004) . The
difference between addresses is 4 bytes. Since the size of
int is 4 bytes, therefore the increment between ptr1 and
ptr2 is given by (4/4) = 1
int main()
{
int x = 6; // Integer variable declaration
int N = 4;

int *ptr1, *ptr2;

ptr1 = &N; // stores address of N


ptr2 = &x; // stores address of x

printf(" ptr1 = %u, ptr2 = %u\n", ptr1, ptr2);

// Subtraction of ptr2 and ptr1


x = ptr1 - ptr2;

printf("Subtraction of ptr1 “
"& ptr2 is %d\n",
x);

return 0;
}
Comparison of Pointers
• >, >=, <, <=, ==, !=
• Step 1: Initialize the integer values and point
these integer values to the pointer.
• Step 2: Now, check the condition by using
comparison or relational operators on pointer
variables.
• Step 3: Display the output.
// C Program to illustrare pointer comparision
#include <stdio.h>

int main()
{
// declaring array
int arr[5];

// declaring pointer to array name


int* ptr1 = &arr;
// declaring pointer to first element
int* ptr2 = &arr[0];

if (ptr1 == ptr2) {
printf("Pointer to Array Name and First Element "
"are Equal.");
}
else {
printf("Pointer to Array Name and First Element "
"are not Equal.");
}

return 0;
}
Comparison to NULL
• A pointer can be compared or assigned a NULL value irrespective of what is the pointer
type. Such pointers are called NULL pointers.

int main()
{
int* ptr = NULL;

if (ptr == NULL) {
printf("The pointer is NULL");
}
else {
printf("The pointer is not NULL");
}
return 0;
}
Pointers & Arrays
• int myNumbers[4] = {25, 50, 75, 100};
int i;

for (i = 0; i < 4; i++) {


printf("%d\n", myNumbers[i]);
}
• name of an array, is actually a pointer to
the first element of the array.
int myNumbers[4] = {25, 50, 75, 100};
printf("%p\n", myNumbers);
printf("%p\n", &myNumbers[0]);

int myNumbers[4] = {25, 50, 75, 100};


printf("%d\n", *(myNumbers + 1));
printf("%d", *(myNumbers + 2));
• int myNumbers[4] = {25, 50, 75, 100};
int *ptr = myNumbers;
int i;
for (i = 0; i < 4; i++) {
printf("%d\n", *(ptr + i));
}
• int myNumbers[4] = {25, 50, 75, 100};

// Change the value of the first element to 13


*myNumbers = 13;

// Change the value of the second element to 17


*(myNumbers +1) = 17;

printf("%d\n", *myNumbers);

printf("%d\n", *(myNumbers + 1));


Array of Pointers
• A pointer array is a homogeneous collection of
indexed pointer variables that are references
to a memory location.
• pointer_type *array_name [array_size];
// C program to demonstrate the use of array of pointers
#include <stdio.h>

int main()
{
// declaring some temp variables
int var1 = 10;
int var2 = 20;
int var3 = 30;

// array of pointers to integers


int* ptr_arr[3] = { &var1, &var2, &var3 };

// traversing using loop


for (int i = 0; i < 3; i++) {
printf("Value of var%d: %d\tAddress: %p\n", i + 1, *ptr_arr[i], ptr_arr[i]);
}

return 0;
}
Array of Pointers to Character
• One of the main applications of the array of
pointers is to store multiple strings as an array
of pointers to characters.
//C Program to print Array of strings without array of pointers
#include <stdio.h>
int main()
{
char str[3][10] = { "Geek", "Geeks", "Geekfor" };

printf("String array Elements are:\n");

for (int i = 0; i < 3; i++) {


printf("%s\n", str[i]);
}

return 0;
}
// C Program to print Array of strings with array of pointers
#include <stdio.h>
int main()
{
// Declare an array of pointers to characters
char* arr[] = { "geek", "Geeks", "Geeksfor" };

// Print each string and its address


for (int i = 0; i < 3; i++) {
printf("%s\n", arr[i]);
}

// Print addresses of each string


for (int i = 0; i < 3; i++) {
printf("Address of arr[%d]: %p\n", i, (void*)arr[i]);
}
return 0;
}
Pointers and Funtions
• A function pointer is a type of pointer that stores the
address of a function, allowing functions to be passed
as arguments and invoked dynamically.
• It is useful in techniques such as callback functions,
event-driven programs, and polymorphism.
Function Pointer Declaration
return_type (*pointer_name)(parameter_types);
Ex: int (*fpr)(int, int);
Initialization
pointer_name = &function_name or
pointer_name = function_name
Properties of Function Pointer
• Points to the memory address of a function in the code
segment.
• Requires the exact function signature (return type and
parameter list).
• Can point to different functions with matching
signatures.
• Cannot perform arithmetic operations like increment
or decrement.
• Supports array-like functionality for tables of function
pointers.
#include <stdio.h>

int add(int a, int b) {


return a + b;
}

int main() {

// Declare a function pointer that matches the signature of add() fuction


int (*fptr)(int, int);

// Assign to add()
fptr = &add;

// Call the function via ptr


printf("%d", fptr(10, 5));

return 0;
}
Dynamic Memory Allocation
• It allows you to allocate memory at runtime.
• Ex: size of an array problem
• Dynamic memory allocation is possible in C by using
4 library functions provided by <stdlib.h> library
malloc()
calloc()
free()
realloc()
malloc()
• The malloc() (stands for memory allocation) function is used
to allocate a single block of contiguous memory on the heap
at runtime.
• The memory allocated by malloc() is uninitialized, meaning it
contains garbage values.
• malloc function returns a null pointer if it couldn't allocate the
requested amount of memory.
calloc()
• The calloc() (stands for contiguous allocation) function is
similar to malloc(), but it initializes the allocated memory to
zero. It is used when you need memory with default zero
values.
free()
• The memory allocated using functions malloc() and calloc() is
not de-allocated on their own. The free() function is used to
release dynamically allocated memory back to the operating
system.
realloc()
• The realloc() function modifies the allocated memory size to a
new size by the malloc() and calloc() functions.
• If enough space doesn't exist in the current block's memory to
expand, a new block is allocated for the total size of the
reallocation, then copies the existing data to the new block
and frees the old block.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void main()
{
char *mem_alloc;
//memory allocated dynamically
mem_alloc = malloc( 15 * sizeof(char) );

if(mem_alloc== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_alloc, “sona”);
}

printf("Dynamically allocated memory content : %s\n", mem_alloc );


free(mem_alloc);
}
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void main()
{
char *mem_alloc;
//memory allocated dynamically
mem_alloc = calloc( 15 * sizeof(char) );

if(mem_alloc== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_alloc, “sona”);
}

printf("Dynamically allocated memory content : %s\n", mem_alloc );


free(mem_alloc);
}
void main()
{
char *mem_alloc;
mem_alloc = malloc( 20 * sizeof(char) );
if( mem_alloc == NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_alloc,“Sona");
}
printf("Dynamically allocated memory content : " \ "%s\n", mem_alloc );
mem_alloc=realloc(mem_alloc,100*sizeof(char));
if( mem_alloc == NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_alloc,"space is extended upto 100 characters");
}
printf("Resized memory : %s\n", mem_alloc );
free(mem_alloc);
}

You might also like