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

Lecture 3.1.3 Pointer and Array, Pointer and Function (2)

Pointer and Array

Uploaded by

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

Lecture 3.1.3 Pointer and Array, Pointer and Function (2)

Pointer and Array

Uploaded by

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

UNIVERSITY INSTITUTE OF ENGINEERING

DEPARTMENT- ACADEMIC UNITS


FIRST YEAR ENGINEERING PROGRAMMES
Subject Name : Introduction to Problem Solving
Subject Code: 24CSH-101

Pointers: Functions returning Pointer, Storage DISCOVER . LEARN . EMPOWER


Classes
Introduction to
Problem Solving

Course Objectives

The course aims to provide exposure to problem-


solving through programming.

The course aims to raise the programming skills


of students via logic building capability.

With knowledge of C programming language,


students would be able to model real world
problems. 2
Course
Outcomes
CO Course Outcome
Number

CO1 Remember the concepts related to fundamentals of C language,


draw flowcharts and write algorithm/pseudocode.

CO2 Understand the way of execution and debug programs in C lan-


guage.
CO3 Apply various constructs, loops, functions to solve mathematical
and scientific problem.

CO4 Analyze the dynamic behavior of memory by the use of pointers.

CO5 Design and develop modular programs for real world problems us-
ing control structure and selection structure.

3
ASSESSMENT PATTERN
The performance of students is evaluated as follows:

Theory Practical
Continuous Internal As- Semester End Examina- Continuous Internal Semester End Exam-
Components sessment (CAE) tion (SEE) Assessment (CAE) ination (SEE)

Marks 40 60 60 40
Total Marks 100 100

4
Pointers and Arrays
• When an array is declared, compiler allocates sufficient amount of memory to contain all the elements of the
array.
• Base address i.e address of the first element of the array is also allocated by the compiler.
• Suppose we declare an array arr,
• int arr[5] = { 1, 2, 3, 4, 5 };
• Assuming that the base address of arr is 1000 and each integer requires two bytes, the five elements will be
stored as follows:

• Here variable arr will give the base address, which is a constant pointer pointing to the first element of the
array, arr[0]. Hence arr contains the address of arr[0] i.e 1000. In short, arr has two purpose - it is the name of
the array and it acts as a pointer pointing towards the first element in the array.
• arr is equal to &arr[0] by default
5
• We can also declare a pointer of type int to point to the array arr.
int *p;
p = arr;
// or,
p = &arr[0]; //both the statements are equivalent.
• Now we can access every element of the array arr using p++ to move
from one element to another.
• NOTE: You cannot decrement a pointer once incremented. p-- won't
work.

6
Pointer to Array
As studied above, we can use a pointer to point to an array, and then we can use that pointer to access the array
elements.
Lets have an example,
#include <stdio.h>
int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}
return 0;
}
In the above program, the pointer *p will print all the values stored in the array one by one. We can also use the Base
address (a in above case) to act as a pointer and print all the values.
7
• The generalized form for using pointer with an array *(a+i) is same as a[i].

Source: https://www.studytonight.com/c/pointers-with-array.php

8
Pointer to Multidimensional
Array
• A multidimensional array is of form, a[i][j].
• Lets see how we can make a pointer point to such an array.
• As we know now, name of the array gives its base address.
• In a[i][j], a will give the base address of this array, even a + 0 + 0 will also
give the base address, that is the address of a[0][0] element.
• Here is the generalized form for using pointer with multidimensional
arrays.
*(*(a + i) + j)
which is same as,
a[i][j]
9
Array of Pointers
• We can also have array of pointers.
• Pointers are very helpful in handling character array with rows of varying length.
• Example:
char *name[3] = {
"Adam",
"chris",
"Deniel"
};
//Now lets see same array without using pointer
char name[3][20] = {
"Adam",
"chris", Source: https://www.studytonight.com/c/pointers-with-array.php
"Deniel"
};
10
• In the second approach memory wastage is more, hence it is prefered
to use pointer in such cases.

• Note: When we say memory wastage, it doesn't means that the


strings will start occupying less space, no, characters will take the
same space, but when we define array of characters, a contiguous
memory space is located equal to the maximum size of the array,
which is a wastage, which can be avoided if we use pointers instead.

11
• Example: Array of Pointers
#include <stdio.h>
const int MAX = 3;
int main ()
{
int var[] = {10, 100, 200};
int i;
for (i = 0; i < MAX; i++)
{
printf("Value of var[%d] = %d\n", i, var[i] );
}
return 0;
}
Output:
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
12
Call by Value Vs Call by Address
Call by Value Call by Reference

The actual arguments can be variable The actual arguments can only be
or constant. variable.
The values of actual argument are The reference of actual argument are
sent to formal argument which are sent to formal argument which are
normal variables. pointer variables.
Any changes made by formal Any changes made by formal
arguments will not reflect to actual arguments will reflect to actual
arguments. arguments.

13
Example: Passing Pointers to Functions
#include <stdio.h>
void addOne(int* ptr) {
(*ptr)++; // adding 1 to *ptr Output:
}

int main()
{
int* p, i = 10;
p = &i;
addOne(p);

printf("%d", *p); // 11
return 0;
}
14
Explanation of the Program:
Here, the value stored at p, *p, is 10 initially.
We then passed the pointer p to the addOne() function. The ptr pointer
gets this address in the addOne() function.
Inside the function, we increased the value stored at ptr by 1 using
(*ptr)++;. Since ptr and p pointers both have the same address, *p
inside main() is also 11.

15
Function Returning a Pointer
• Like normal variable, a function can also return reference or address. When function
returns reference or address, the return type of function must be pointer type.

Syntax for function returning pointer:

return-type *function-name(argument list)


{
----------
body of function
----------
}
16
Example: Write a C program for function returning pointer
#include<stdio.h> Output:
int *reference(int *);
int main()
{
int A=10;
int *ptr;
printf("\nAddress of %d in main() is %x",A,&A);
ptr = reference(&A);
printf("\nAddress of %d in reference() was %x",A,ptr);
return 0;
}
int *reference(int *n)
{
return n;
}
17
• A function can also return a pointer to the calling function.
• In this case you must be careful, because local variables of function
doesn't live outside the function.
• They have scope only inside the function.
• Hence if you return a pointer connected to a local variable, that
pointer will be pointing to nothing when the function ends.

18
Summary

In call by reference, the When an array is declared,


In call by value method, the
address of the variable is compiler allocates sufficient
value of the actual
passed into the function call amount of memory to
parameters is copied into
as the actual parameter. contain all the elements of
the formal parameters.
the array.

C programming allows
passing a pointer to a
function. To do so, simply C also allows to return a
declare the function pointer from a function.
parameter as a pointer
type.

19
Frequently Asked question
Q1:What will the Output of the Program?
#include<stdio.h>
int main()
{
printf("%d", sizeof(void *));
return 0;
}
Output:

20
2) What will be the Output?
#include<stdio.h>
void function(char**);
int main()
{
char *arr[] = { "ant", "bat", "cat", "dog", "egg", "fly" };
function(arr);
return 0; Output:
}
void function(char **ptr)
{
char *ptr1;
ptr1 = (ptr += sizeof(int))[-2];
printf("%s\n", ptr1);
}
return (0);}
21
Q3) What is “&” and “*” operators in C?
Ans:
1. “*” Operator is used as pointer to a variable. Example: * a where * is
pointer to the variable a.
2. & operator is used to get the address of the variable. Example: &a will give
address of a.

Q4) WHAT IS VOID POINTER IN C?


Ans:
3. Void pointer is a generic pointer that can be used to point another variable of
any data type.
4. Void pointer can store the address of variable belonging to any of the data type.
So, void pointer is also called as general purpose pointer.

22
Assessment Questions:
1. What will be the output of the C program?
#include<stdio.h>
int main(){
int a = 25, b;
int *ptr, *ptr1;
ptr = &a;
ptr1 = &b;
b = 36;
printf("%d %d",*ptr, *ptr1);
return 0;
}

2. What will be the output of the C program?

#include<stdio.h>
int main(){
int * ptr ;
printf("%d", sizeof(ptr));
return 0;
}
23
3. What will be the output of the C program?
#include<stdio.h>
int main()
{
char *str = "His";
int i;
for(i = 0; i < strlen(str); i++)
printf("%s", str++);
return 0;
}

24
Discussion forum.
• Write a program in C to add numbers using call by reference.

25
REFERENCES
Reference Books
1. Programming in C by Reema Thareja.
2. Programming in ANSI C by E. Balaguruswamy, Tata McGraw Hill.
3. Programming with C (Schaum's Outline Series) by Byron Gottfried Jitender
Chhabra, Tata McGraw Hill.
4. The C Programming Language by Brian W. Kernighan, Dennis Ritchie, Pearson
education.

Websites:
5. https://www.programiz.com/c-programming/c-pointer-functions
6. https://www.studytonight.com/c/pointer-with-function-in-c.php
7. http://www.tutorialdost.com/C-Programming-Tutorial/17-C-Pointers.aspx

YouTube Links:
8. http://www.digimat.in/nptel/courses/video/106104128/L38.html

26
THANK YOU

You might also like